This question already has an answer here:
I have a tuple of tuples - for example:
tupleOfTuples = ((1, 2), (3, 4), (5,))
I want to convert this into a flat, one-dimensional list of all the elements in order:
[1, 2, 3, 4, 5]
I've been trying to accomplish this with list comprehension. But I can't seem to figure it out. I was able to accomplish it with a for-each loop:
myList = []
for tuple in tupleOfTuples:
myList = myList + list(tuple)
But I feel like there must be a way to do this with a list comprehension.
A simple [list(tuple) for tuple in tupleOfTuples]
just gives you a list of lists, instead of individual elements. I thought I could perhaps build on this by using the unpacking operator to then unpack the list, like so:
[*list(tuple) for tuple in tupleOfTuples]
or
[*(list(tuple)) for tuple in tupleOfTuples]
... but that didn't work. Any ideas? Or should I just stick to the loop?
it's typically referred to as flattening a nested structure.
Just to demonstrate efficiency:
ETA: Please don't use
tuple
as a variable name, it shadows built-in.You're chaining the tuples together:
Should be pretty readable if you're familiar with
itertools
, and without the explicitlist
you even have your result in generator form.Another solution using itertools.chain
Most of these answers will only work for a single level of flattening. For a more comprehensive solution, try this (from http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html):
I like using 'reduce' in this situation (this is what reduce made for!)
Just use
sum
if you don't have a lot of tuples.If you do have a lot of tuples, use list comprehension or
chain.from_iterable
to prevent the quadratic behavior ofsum
.Micro-benchmarks:
Python 2.6
Long tuple of short tuples
Short tuple of long tuples
Python 3.1
Long tuple of short tuples
Short tuple of long tuples
Observation:
sum
is faster if the outer tuple is short.list(chain.from_iterable(x))
is faster if the outer tuple is long.