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?

If human space travel is limited by the G force vulnerability, is there a way to counter G forces?

What reasons are there for a Capitalist to oppose a 100% inheritance tax?

What killed these X2 caps?

One verb to replace 'be a member of' a club

What type of content (depth/breadth) is expected for a short presentation for Asst Professor interview in the UK?

Should I tell management that I intend to leave due to bad software development practices?

Is there an expression that means doing something right before you will need it rather than doing it in case you might need it?

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

What is the idiomatic way to say "clothing fits"?

Do scales need to be in alphabetical order?

What are some good books on Machine Learning and AI like Krugman, Wells and Graddy's "Essentials of Economics"

Is this a hacking script in function.php?

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

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

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

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

What is the most common color to indicate the input-field is disabled?

Unlock My Phone! February 2018

Personal Teleportation: From Rags to Riches

Are there any examples of a variable being normally distributed that is *not* due to the Central Limit Theorem?

What do you call someone who asks many questions?

Forgetting the musical notes while performing in concert

Venezuelan girlfriend wants to travel the USA to be with me. What is the process?



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 8 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

                                名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

                                格濟夫卡 參考資料 导航菜单51°3′40″N 34°2′21″E / 51.06111°N 34.03917°E / 51.06111; 34.03917ГезівкаПогода в селі 编辑或修订