Most pythonic way to combine elements of arbitrary lists into a single listBinary index tree optimizationShortest path in imageGenerate set of random numbers and remove lowestProcessing a sequence of additions and deletionsGame where two players take turns picking numbers until a target sum (part 2)Finding line numbers of duplicate lines in a log fileSparse matrix compressed sparse row (CSR) in Python 2.7Python - One-to-many dictionary mappingAppointment Scheduleincrease the efficiency of a matching algorithm

How can I deal with my CEO asking me to hire someone with a higher salary than me, a co-founder?

Plagiarism or not?

How much of data wrangling is a data scientist's job?

Why didn't Miles's spider sense work before?

Can a virus destroy the BIOS of a modern computer?

Detention in 1997

Ambiguity in the definition of entropy

Expand and Contract

Does the Idaho Potato Commission associate potato skins with healthy eating?

Why was the shrinking from 8″ made only to 5.25″ and not smaller (4″ or less)?

When (not how or why) to calculate Big O of an algorithm

Is it inappropriate for a student to attend their mentor's dissertation defense?

ssTTsSTtRrriinInnnnNNNIiinngg

What mechanic is there to disable a threat instead of killing it?

Apex Framework / library for consuming REST services

GFCI outlets - can they be repaired? Are they really needed at the end of a circuit?

Forming a German sentence with/without the verb at the end

Valid term from quadratic sequence?

Am I breaking OOP practice with this architecture?

Avoiding the "not like other girls" trope?

Short story with a alien planet, government officials must wear exploding medallions

How to add frame around section using titlesec?

What about the virus in 12 Monkeys?

Do UK voters know if their MP will be the Speaker of the House?



Most pythonic way to combine elements of arbitrary lists into a single list


Binary index tree optimizationShortest path in imageGenerate set of random numbers and remove lowestProcessing a sequence of additions and deletionsGame where two players take turns picking numbers until a target sum (part 2)Finding line numbers of duplicate lines in a log fileSparse matrix compressed sparse row (CSR) in Python 2.7Python - One-to-many dictionary mappingAppointment Scheduleincrease the efficiency of a matching algorithm













13












$begingroup$


I have a list of lists which represents the options I can chose from.



I have a sequence of indices which represent which option lists I want to take elements from, and in which order.



E.g. if I have



choices = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

sequence = [ 2, 0, 1, 1 ]


I want my output to be



[7, 8, 9, 1, 2, 3, 4, 5, 6, 4, 5, 6]
#index 2 index 0 index 1 index 1


I have found three possible solutions:



choice = sum( ( choices[i] for i in sequence ), [] )

choice = reduce( operator.add, ( choices[i] for i in sequence ) )

choice = [ element for i in sequence for element in choices[i] ]


I would like to know which of these do people find the most pythonic and to know if there are any other elegant solutions.










share|improve this question











$endgroup$











  • $begingroup$
    Per the style guide, consider removing the extraneous whitespace inside brackets.
    $endgroup$
    – jonrsharpe
    Jul 10 '14 at 14:08










  • $begingroup$
    @jonrsharpe this per the company style guide, unfortunately.
    $endgroup$
    – Griffin
    Jul 10 '14 at 14:10










  • $begingroup$
    Ah, I see - it's probably worth mentioning that you're following such a thing! Do you need the whole list choice, or would an iterable do? What do you do with it next?
    $endgroup$
    – jonrsharpe
    Jul 10 '14 at 14:12










  • $begingroup$
    @jonrsharpe an iterable is fine.
    $endgroup$
    – Griffin
    Jul 10 '14 at 14:13










  • $begingroup$
    assuming that they all do the same thing, this may be a matter of opinion, or this whole question could fall under "code not written (yet)"
    $endgroup$
    – Malachi
    Jul 10 '14 at 14:30















13












$begingroup$


I have a list of lists which represents the options I can chose from.



I have a sequence of indices which represent which option lists I want to take elements from, and in which order.



E.g. if I have



choices = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

sequence = [ 2, 0, 1, 1 ]


I want my output to be



[7, 8, 9, 1, 2, 3, 4, 5, 6, 4, 5, 6]
#index 2 index 0 index 1 index 1


I have found three possible solutions:



choice = sum( ( choices[i] for i in sequence ), [] )

choice = reduce( operator.add, ( choices[i] for i in sequence ) )

choice = [ element for i in sequence for element in choices[i] ]


I would like to know which of these do people find the most pythonic and to know if there are any other elegant solutions.










share|improve this question











$endgroup$











  • $begingroup$
    Per the style guide, consider removing the extraneous whitespace inside brackets.
    $endgroup$
    – jonrsharpe
    Jul 10 '14 at 14:08










  • $begingroup$
    @jonrsharpe this per the company style guide, unfortunately.
    $endgroup$
    – Griffin
    Jul 10 '14 at 14:10










  • $begingroup$
    Ah, I see - it's probably worth mentioning that you're following such a thing! Do you need the whole list choice, or would an iterable do? What do you do with it next?
    $endgroup$
    – jonrsharpe
    Jul 10 '14 at 14:12










  • $begingroup$
    @jonrsharpe an iterable is fine.
    $endgroup$
    – Griffin
    Jul 10 '14 at 14:13










  • $begingroup$
    assuming that they all do the same thing, this may be a matter of opinion, or this whole question could fall under "code not written (yet)"
    $endgroup$
    – Malachi
    Jul 10 '14 at 14:30













13












13








13


3



$begingroup$


I have a list of lists which represents the options I can chose from.



I have a sequence of indices which represent which option lists I want to take elements from, and in which order.



E.g. if I have



choices = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

sequence = [ 2, 0, 1, 1 ]


I want my output to be



[7, 8, 9, 1, 2, 3, 4, 5, 6, 4, 5, 6]
#index 2 index 0 index 1 index 1


I have found three possible solutions:



choice = sum( ( choices[i] for i in sequence ), [] )

choice = reduce( operator.add, ( choices[i] for i in sequence ) )

choice = [ element for i in sequence for element in choices[i] ]


I would like to know which of these do people find the most pythonic and to know if there are any other elegant solutions.










share|improve this question











$endgroup$




I have a list of lists which represents the options I can chose from.



I have a sequence of indices which represent which option lists I want to take elements from, and in which order.



E.g. if I have



choices = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

sequence = [ 2, 0, 1, 1 ]


I want my output to be



[7, 8, 9, 1, 2, 3, 4, 5, 6, 4, 5, 6]
#index 2 index 0 index 1 index 1


I have found three possible solutions:



choice = sum( ( choices[i] for i in sequence ), [] )

choice = reduce( operator.add, ( choices[i] for i in sequence ) )

choice = [ element for i in sequence for element in choices[i] ]


I would like to know which of these do people find the most pythonic and to know if there are any other elegant solutions.







python performance






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 5 mins ago









Community

1




1










asked Jul 10 '14 at 14:02









GriffinGriffin

171115




171115











  • $begingroup$
    Per the style guide, consider removing the extraneous whitespace inside brackets.
    $endgroup$
    – jonrsharpe
    Jul 10 '14 at 14:08










  • $begingroup$
    @jonrsharpe this per the company style guide, unfortunately.
    $endgroup$
    – Griffin
    Jul 10 '14 at 14:10










  • $begingroup$
    Ah, I see - it's probably worth mentioning that you're following such a thing! Do you need the whole list choice, or would an iterable do? What do you do with it next?
    $endgroup$
    – jonrsharpe
    Jul 10 '14 at 14:12










  • $begingroup$
    @jonrsharpe an iterable is fine.
    $endgroup$
    – Griffin
    Jul 10 '14 at 14:13










  • $begingroup$
    assuming that they all do the same thing, this may be a matter of opinion, or this whole question could fall under "code not written (yet)"
    $endgroup$
    – Malachi
    Jul 10 '14 at 14:30
















  • $begingroup$
    Per the style guide, consider removing the extraneous whitespace inside brackets.
    $endgroup$
    – jonrsharpe
    Jul 10 '14 at 14:08










  • $begingroup$
    @jonrsharpe this per the company style guide, unfortunately.
    $endgroup$
    – Griffin
    Jul 10 '14 at 14:10










  • $begingroup$
    Ah, I see - it's probably worth mentioning that you're following such a thing! Do you need the whole list choice, or would an iterable do? What do you do with it next?
    $endgroup$
    – jonrsharpe
    Jul 10 '14 at 14:12










  • $begingroup$
    @jonrsharpe an iterable is fine.
    $endgroup$
    – Griffin
    Jul 10 '14 at 14:13










  • $begingroup$
    assuming that they all do the same thing, this may be a matter of opinion, or this whole question could fall under "code not written (yet)"
    $endgroup$
    – Malachi
    Jul 10 '14 at 14:30















$begingroup$
Per the style guide, consider removing the extraneous whitespace inside brackets.
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:08




$begingroup$
Per the style guide, consider removing the extraneous whitespace inside brackets.
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:08












$begingroup$
@jonrsharpe this per the company style guide, unfortunately.
$endgroup$
– Griffin
Jul 10 '14 at 14:10




$begingroup$
@jonrsharpe this per the company style guide, unfortunately.
$endgroup$
– Griffin
Jul 10 '14 at 14:10












$begingroup$
Ah, I see - it's probably worth mentioning that you're following such a thing! Do you need the whole list choice, or would an iterable do? What do you do with it next?
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:12




$begingroup$
Ah, I see - it's probably worth mentioning that you're following such a thing! Do you need the whole list choice, or would an iterable do? What do you do with it next?
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:12












$begingroup$
@jonrsharpe an iterable is fine.
$endgroup$
– Griffin
Jul 10 '14 at 14:13




$begingroup$
@jonrsharpe an iterable is fine.
$endgroup$
– Griffin
Jul 10 '14 at 14:13












$begingroup$
assuming that they all do the same thing, this may be a matter of opinion, or this whole question could fall under "code not written (yet)"
$endgroup$
– Malachi
Jul 10 '14 at 14:30




$begingroup$
assuming that they all do the same thing, this may be a matter of opinion, or this whole question could fall under "code not written (yet)"
$endgroup$
– Malachi
Jul 10 '14 at 14:30










4 Answers
4






active

oldest

votes


















19












$begingroup$

Unless I actually needed the whole list at once, I would probably use itertools for this:



from itertools import chain

choice = chain.from_iterable(choices[i] for i in sequence)


If you do need the list, you can still use this with an explicit conversion:



choice = list(chain.from_iterable(choices[i] for i in sequence))



Note: this fits pretty close to Nobody's suggestion - here chain.from_iterable is flatten and the generator expression is making the sample.






share|improve this answer









$endgroup$




















    6












    $begingroup$

    I find neither of your solutions very pythonic.



    Using sum to concatenate lists seems like a hack.



    Using reduce looks better but still has the problem of making the selection too verbose to read it fast.



    The last one is far too much. Understanding what it does takes way too long.



    Actually the problem you are solving is two subproblems:



    1. taking a list of samples from the choices collection

    2. flattening the resulting list

    So the code should be more like



    flatten(samples(choices, sequence))


    I am no regular user of python so I can't tell you much about library implementations of flatten and samples but I am quite sure that there are many implementations around on the net (not necessarily under these names though).






    share|improve this answer









    $endgroup$












    • $begingroup$
      Also, although not deprecated per se, reduce has moved from the built-ins to functools in 3.x, which could be interpreted as suggesting its use isn't Pythonic.
      $endgroup$
      – jonrsharpe
      Jul 10 '14 at 14:35










    • $begingroup$
      @jonrsharpe: Given that "Pythonic" often means what GvR thinks, and he doesn't like map/reduce/filter, it's safe to say they aren't pythonic. Nothing that relies on anonymous functions is, really, just look at that syntax.
      $endgroup$
      – Phoshi
      Jul 10 '14 at 15:43






    • 1




      $begingroup$
      Guido doesn't dislike map and filter, he likes them so much that he created a special type of expression that combines them to form generator expressions and comprehensions of various types: list, set, dict; and he's on record as saying most people use reduce when they mean to use sum, and I'd agree.
      $endgroup$
      – Aaron Hall
      Jul 10 '14 at 17:57


















    2












    $begingroup$

    I agree with @jonrsharpe: Use itertools.chain().



    The problem with the first two solutions…



    choice = sum( ( choices[i] for i in sequence ), [] )
    choice = reduce( operator.add, ( choices[i] for i in sequence ) )


    is that adding lists does not scale well, if sequence is long.



    The third solution…



    choice = [ element for i in sequence for element in choices[i] ]


    doesn't suffer from repeated copying like the first two. However, it's less readable than the itertools.chain version.






    share|improve this answer









    $endgroup$




















      1












      $begingroup$

      You want something to be pythonic? It seems you would like to have a one liner. Simple AND elegant is more pythonic in my opinion.



      The "most" pythonic in my opinion would be this:



      choice = []
      for choice_index in sequence:
      if choice_index >= len(choices):
      break
      choice += choices[choice_index]


      For a one-liner? I will wrap it in a function and use that like this for repetitive work.



      def generate_choice_list(choices, sequence):
      choice = []
      for choice_index in sequence:
      if choice_index >= len(choices):
      return []
      choice += choices[choice_index]
      return choice


      This has the added advantage of eliminating wrong entries with the sequence list, like returning empty list for incorrect sequence list.






      share|improve this answer









      $endgroup$













        Your Answer





        StackExchange.ifUsing("editor", function ()
        return StackExchange.using("mathjaxEditing", function ()
        StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
        StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
        );
        );
        , "mathjax-editing");

        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "196"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: false,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: null,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f56650%2fmost-pythonic-way-to-combine-elements-of-arbitrary-lists-into-a-single-list%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        19












        $begingroup$

        Unless I actually needed the whole list at once, I would probably use itertools for this:



        from itertools import chain

        choice = chain.from_iterable(choices[i] for i in sequence)


        If you do need the list, you can still use this with an explicit conversion:



        choice = list(chain.from_iterable(choices[i] for i in sequence))



        Note: this fits pretty close to Nobody's suggestion - here chain.from_iterable is flatten and the generator expression is making the sample.






        share|improve this answer









        $endgroup$

















          19












          $begingroup$

          Unless I actually needed the whole list at once, I would probably use itertools for this:



          from itertools import chain

          choice = chain.from_iterable(choices[i] for i in sequence)


          If you do need the list, you can still use this with an explicit conversion:



          choice = list(chain.from_iterable(choices[i] for i in sequence))



          Note: this fits pretty close to Nobody's suggestion - here chain.from_iterable is flatten and the generator expression is making the sample.






          share|improve this answer









          $endgroup$















            19












            19








            19





            $begingroup$

            Unless I actually needed the whole list at once, I would probably use itertools for this:



            from itertools import chain

            choice = chain.from_iterable(choices[i] for i in sequence)


            If you do need the list, you can still use this with an explicit conversion:



            choice = list(chain.from_iterable(choices[i] for i in sequence))



            Note: this fits pretty close to Nobody's suggestion - here chain.from_iterable is flatten and the generator expression is making the sample.






            share|improve this answer









            $endgroup$



            Unless I actually needed the whole list at once, I would probably use itertools for this:



            from itertools import chain

            choice = chain.from_iterable(choices[i] for i in sequence)


            If you do need the list, you can still use this with an explicit conversion:



            choice = list(chain.from_iterable(choices[i] for i in sequence))



            Note: this fits pretty close to Nobody's suggestion - here chain.from_iterable is flatten and the generator expression is making the sample.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jul 10 '14 at 14:14









            jonrsharpejonrsharpe

            13.2k12858




            13.2k12858























                6












                $begingroup$

                I find neither of your solutions very pythonic.



                Using sum to concatenate lists seems like a hack.



                Using reduce looks better but still has the problem of making the selection too verbose to read it fast.



                The last one is far too much. Understanding what it does takes way too long.



                Actually the problem you are solving is two subproblems:



                1. taking a list of samples from the choices collection

                2. flattening the resulting list

                So the code should be more like



                flatten(samples(choices, sequence))


                I am no regular user of python so I can't tell you much about library implementations of flatten and samples but I am quite sure that there are many implementations around on the net (not necessarily under these names though).






                share|improve this answer









                $endgroup$












                • $begingroup$
                  Also, although not deprecated per se, reduce has moved from the built-ins to functools in 3.x, which could be interpreted as suggesting its use isn't Pythonic.
                  $endgroup$
                  – jonrsharpe
                  Jul 10 '14 at 14:35










                • $begingroup$
                  @jonrsharpe: Given that "Pythonic" often means what GvR thinks, and he doesn't like map/reduce/filter, it's safe to say they aren't pythonic. Nothing that relies on anonymous functions is, really, just look at that syntax.
                  $endgroup$
                  – Phoshi
                  Jul 10 '14 at 15:43






                • 1




                  $begingroup$
                  Guido doesn't dislike map and filter, he likes them so much that he created a special type of expression that combines them to form generator expressions and comprehensions of various types: list, set, dict; and he's on record as saying most people use reduce when they mean to use sum, and I'd agree.
                  $endgroup$
                  – Aaron Hall
                  Jul 10 '14 at 17:57















                6












                $begingroup$

                I find neither of your solutions very pythonic.



                Using sum to concatenate lists seems like a hack.



                Using reduce looks better but still has the problem of making the selection too verbose to read it fast.



                The last one is far too much. Understanding what it does takes way too long.



                Actually the problem you are solving is two subproblems:



                1. taking a list of samples from the choices collection

                2. flattening the resulting list

                So the code should be more like



                flatten(samples(choices, sequence))


                I am no regular user of python so I can't tell you much about library implementations of flatten and samples but I am quite sure that there are many implementations around on the net (not necessarily under these names though).






                share|improve this answer









                $endgroup$












                • $begingroup$
                  Also, although not deprecated per se, reduce has moved from the built-ins to functools in 3.x, which could be interpreted as suggesting its use isn't Pythonic.
                  $endgroup$
                  – jonrsharpe
                  Jul 10 '14 at 14:35










                • $begingroup$
                  @jonrsharpe: Given that "Pythonic" often means what GvR thinks, and he doesn't like map/reduce/filter, it's safe to say they aren't pythonic. Nothing that relies on anonymous functions is, really, just look at that syntax.
                  $endgroup$
                  – Phoshi
                  Jul 10 '14 at 15:43






                • 1




                  $begingroup$
                  Guido doesn't dislike map and filter, he likes them so much that he created a special type of expression that combines them to form generator expressions and comprehensions of various types: list, set, dict; and he's on record as saying most people use reduce when they mean to use sum, and I'd agree.
                  $endgroup$
                  – Aaron Hall
                  Jul 10 '14 at 17:57













                6












                6








                6





                $begingroup$

                I find neither of your solutions very pythonic.



                Using sum to concatenate lists seems like a hack.



                Using reduce looks better but still has the problem of making the selection too verbose to read it fast.



                The last one is far too much. Understanding what it does takes way too long.



                Actually the problem you are solving is two subproblems:



                1. taking a list of samples from the choices collection

                2. flattening the resulting list

                So the code should be more like



                flatten(samples(choices, sequence))


                I am no regular user of python so I can't tell you much about library implementations of flatten and samples but I am quite sure that there are many implementations around on the net (not necessarily under these names though).






                share|improve this answer









                $endgroup$



                I find neither of your solutions very pythonic.



                Using sum to concatenate lists seems like a hack.



                Using reduce looks better but still has the problem of making the selection too verbose to read it fast.



                The last one is far too much. Understanding what it does takes way too long.



                Actually the problem you are solving is two subproblems:



                1. taking a list of samples from the choices collection

                2. flattening the resulting list

                So the code should be more like



                flatten(samples(choices, sequence))


                I am no regular user of python so I can't tell you much about library implementations of flatten and samples but I am quite sure that there are many implementations around on the net (not necessarily under these names though).







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jul 10 '14 at 14:13









                NobodyNobody

                4,1871738




                4,1871738











                • $begingroup$
                  Also, although not deprecated per se, reduce has moved from the built-ins to functools in 3.x, which could be interpreted as suggesting its use isn't Pythonic.
                  $endgroup$
                  – jonrsharpe
                  Jul 10 '14 at 14:35










                • $begingroup$
                  @jonrsharpe: Given that "Pythonic" often means what GvR thinks, and he doesn't like map/reduce/filter, it's safe to say they aren't pythonic. Nothing that relies on anonymous functions is, really, just look at that syntax.
                  $endgroup$
                  – Phoshi
                  Jul 10 '14 at 15:43






                • 1




                  $begingroup$
                  Guido doesn't dislike map and filter, he likes them so much that he created a special type of expression that combines them to form generator expressions and comprehensions of various types: list, set, dict; and he's on record as saying most people use reduce when they mean to use sum, and I'd agree.
                  $endgroup$
                  – Aaron Hall
                  Jul 10 '14 at 17:57
















                • $begingroup$
                  Also, although not deprecated per se, reduce has moved from the built-ins to functools in 3.x, which could be interpreted as suggesting its use isn't Pythonic.
                  $endgroup$
                  – jonrsharpe
                  Jul 10 '14 at 14:35










                • $begingroup$
                  @jonrsharpe: Given that "Pythonic" often means what GvR thinks, and he doesn't like map/reduce/filter, it's safe to say they aren't pythonic. Nothing that relies on anonymous functions is, really, just look at that syntax.
                  $endgroup$
                  – Phoshi
                  Jul 10 '14 at 15:43






                • 1




                  $begingroup$
                  Guido doesn't dislike map and filter, he likes them so much that he created a special type of expression that combines them to form generator expressions and comprehensions of various types: list, set, dict; and he's on record as saying most people use reduce when they mean to use sum, and I'd agree.
                  $endgroup$
                  – Aaron Hall
                  Jul 10 '14 at 17:57















                $begingroup$
                Also, although not deprecated per se, reduce has moved from the built-ins to functools in 3.x, which could be interpreted as suggesting its use isn't Pythonic.
                $endgroup$
                – jonrsharpe
                Jul 10 '14 at 14:35




                $begingroup$
                Also, although not deprecated per se, reduce has moved from the built-ins to functools in 3.x, which could be interpreted as suggesting its use isn't Pythonic.
                $endgroup$
                – jonrsharpe
                Jul 10 '14 at 14:35












                $begingroup$
                @jonrsharpe: Given that "Pythonic" often means what GvR thinks, and he doesn't like map/reduce/filter, it's safe to say they aren't pythonic. Nothing that relies on anonymous functions is, really, just look at that syntax.
                $endgroup$
                – Phoshi
                Jul 10 '14 at 15:43




                $begingroup$
                @jonrsharpe: Given that "Pythonic" often means what GvR thinks, and he doesn't like map/reduce/filter, it's safe to say they aren't pythonic. Nothing that relies on anonymous functions is, really, just look at that syntax.
                $endgroup$
                – Phoshi
                Jul 10 '14 at 15:43




                1




                1




                $begingroup$
                Guido doesn't dislike map and filter, he likes them so much that he created a special type of expression that combines them to form generator expressions and comprehensions of various types: list, set, dict; and he's on record as saying most people use reduce when they mean to use sum, and I'd agree.
                $endgroup$
                – Aaron Hall
                Jul 10 '14 at 17:57




                $begingroup$
                Guido doesn't dislike map and filter, he likes them so much that he created a special type of expression that combines them to form generator expressions and comprehensions of various types: list, set, dict; and he's on record as saying most people use reduce when they mean to use sum, and I'd agree.
                $endgroup$
                – Aaron Hall
                Jul 10 '14 at 17:57











                2












                $begingroup$

                I agree with @jonrsharpe: Use itertools.chain().



                The problem with the first two solutions…



                choice = sum( ( choices[i] for i in sequence ), [] )
                choice = reduce( operator.add, ( choices[i] for i in sequence ) )


                is that adding lists does not scale well, if sequence is long.



                The third solution…



                choice = [ element for i in sequence for element in choices[i] ]


                doesn't suffer from repeated copying like the first two. However, it's less readable than the itertools.chain version.






                share|improve this answer









                $endgroup$

















                  2












                  $begingroup$

                  I agree with @jonrsharpe: Use itertools.chain().



                  The problem with the first two solutions…



                  choice = sum( ( choices[i] for i in sequence ), [] )
                  choice = reduce( operator.add, ( choices[i] for i in sequence ) )


                  is that adding lists does not scale well, if sequence is long.



                  The third solution…



                  choice = [ element for i in sequence for element in choices[i] ]


                  doesn't suffer from repeated copying like the first two. However, it's less readable than the itertools.chain version.






                  share|improve this answer









                  $endgroup$















                    2












                    2








                    2





                    $begingroup$

                    I agree with @jonrsharpe: Use itertools.chain().



                    The problem with the first two solutions…



                    choice = sum( ( choices[i] for i in sequence ), [] )
                    choice = reduce( operator.add, ( choices[i] for i in sequence ) )


                    is that adding lists does not scale well, if sequence is long.



                    The third solution…



                    choice = [ element for i in sequence for element in choices[i] ]


                    doesn't suffer from repeated copying like the first two. However, it's less readable than the itertools.chain version.






                    share|improve this answer









                    $endgroup$



                    I agree with @jonrsharpe: Use itertools.chain().



                    The problem with the first two solutions…



                    choice = sum( ( choices[i] for i in sequence ), [] )
                    choice = reduce( operator.add, ( choices[i] for i in sequence ) )


                    is that adding lists does not scale well, if sequence is long.



                    The third solution…



                    choice = [ element for i in sequence for element in choices[i] ]


                    doesn't suffer from repeated copying like the first two. However, it's less readable than the itertools.chain version.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jul 10 '14 at 22:16









                    200_success200_success

                    131k17157422




                    131k17157422





















                        1












                        $begingroup$

                        You want something to be pythonic? It seems you would like to have a one liner. Simple AND elegant is more pythonic in my opinion.



                        The "most" pythonic in my opinion would be this:



                        choice = []
                        for choice_index in sequence:
                        if choice_index >= len(choices):
                        break
                        choice += choices[choice_index]


                        For a one-liner? I will wrap it in a function and use that like this for repetitive work.



                        def generate_choice_list(choices, sequence):
                        choice = []
                        for choice_index in sequence:
                        if choice_index >= len(choices):
                        return []
                        choice += choices[choice_index]
                        return choice


                        This has the added advantage of eliminating wrong entries with the sequence list, like returning empty list for incorrect sequence list.






                        share|improve this answer









                        $endgroup$

















                          1












                          $begingroup$

                          You want something to be pythonic? It seems you would like to have a one liner. Simple AND elegant is more pythonic in my opinion.



                          The "most" pythonic in my opinion would be this:



                          choice = []
                          for choice_index in sequence:
                          if choice_index >= len(choices):
                          break
                          choice += choices[choice_index]


                          For a one-liner? I will wrap it in a function and use that like this for repetitive work.



                          def generate_choice_list(choices, sequence):
                          choice = []
                          for choice_index in sequence:
                          if choice_index >= len(choices):
                          return []
                          choice += choices[choice_index]
                          return choice


                          This has the added advantage of eliminating wrong entries with the sequence list, like returning empty list for incorrect sequence list.






                          share|improve this answer









                          $endgroup$















                            1












                            1








                            1





                            $begingroup$

                            You want something to be pythonic? It seems you would like to have a one liner. Simple AND elegant is more pythonic in my opinion.



                            The "most" pythonic in my opinion would be this:



                            choice = []
                            for choice_index in sequence:
                            if choice_index >= len(choices):
                            break
                            choice += choices[choice_index]


                            For a one-liner? I will wrap it in a function and use that like this for repetitive work.



                            def generate_choice_list(choices, sequence):
                            choice = []
                            for choice_index in sequence:
                            if choice_index >= len(choices):
                            return []
                            choice += choices[choice_index]
                            return choice


                            This has the added advantage of eliminating wrong entries with the sequence list, like returning empty list for incorrect sequence list.






                            share|improve this answer









                            $endgroup$



                            You want something to be pythonic? It seems you would like to have a one liner. Simple AND elegant is more pythonic in my opinion.



                            The "most" pythonic in my opinion would be this:



                            choice = []
                            for choice_index in sequence:
                            if choice_index >= len(choices):
                            break
                            choice += choices[choice_index]


                            For a one-liner? I will wrap it in a function and use that like this for repetitive work.



                            def generate_choice_list(choices, sequence):
                            choice = []
                            for choice_index in sequence:
                            if choice_index >= len(choices):
                            return []
                            choice += choices[choice_index]
                            return choice


                            This has the added advantage of eliminating wrong entries with the sequence list, like returning empty list for incorrect sequence list.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jul 11 '14 at 13:50









                            thiruvenkadamthiruvenkadam

                            1111




                            1111



























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Code Review Stack Exchange!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                Use MathJax to format equations. MathJax reference.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f56650%2fmost-pythonic-way-to-combine-elements-of-arbitrary-lists-into-a-single-list%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                बाताम इन्हें भी देखें सन्दर्भ दिक्चालन सूची1°05′00″N 104°02′0″E / 1.08333°N 104.03333°E / 1.08333; 104.033331°05′00″N 104°02′0″E / 1.08333°N 104.03333°E / 1.08333; 104.03333

                                Why is the 'in' operator throwing an error with a string literal instead of logging false?Why can't I use switch statement on a String?Python join: why is it string.join(list) instead of list.join(string)?Multiline String Literal in C#Why does comparing strings using either '==' or 'is' sometimes produce a different result?How to initialize an array's length in javascript?How can I print literal curly-brace characters in python string and also use .format on it?Why does ++[[]][+[]]+[+[]] return the string “10”?Why is char[] preferred over String for passwords?Why does this code using random strings print “hello world”?jQuery.inArray(), how to use it right?

                                How can we generalize the fact of finite dimensional vector space to an infinte dimensional case?$k[x]$-module and cyclic module over a finite dimensional vector spaceSubspace of a finite dimensional space is finite dimensionalIf V is an infinite-dimensional vector space, and S is an infinite-dimensional subspace of V, must the dimension of V/S be finite? ExplainWhy is an infinite dimensional space so different than a finite dimensional one?base for finite dimensional vector space is not infinite dimensional vector space?Any finite-dimensional vector space is the dual space of anotherHaving Trouble Understanding Meaning Of A Finite-Dimensional Vector SpaceProve that “Every subspaces of a finite-dimensional vector space is finite-dimensional”Ring as a finite dimensional Vector space over a field KQuestion regarding basis and dimension