HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

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

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pythonicelementscombinearbitraryintowaysinglelistslistmost

Problem

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.

Solution

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.

Code Snippets

from itertools import chain

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

Context

StackExchange Code Review Q#56650, answer score: 19

Revisions (0)

No revisions yet.