This question already has an answer here:
Is the a short syntax for joining a list of lists into a single list( or iterator) in python?
For example I have a list as follows and I want to iterate over a,b and c.
x = [["a","b"], ["c"]]
The best I can come up with is as follows.
result = []
[ result.extend(el) for el in x]
for el in result:
print el
This is known as flattening, and there are a LOT of implementations out there:
How about this, although it will only work for 1 level deep nesting:
From those links, apparently the most complete-fast-elegant-etc implementation is the following:
There's always reduce (being deprecated to functools):
Unfortunately the plus operator for list concatenation can't be used as a function -- or fortunate, if you prefer lambdas to be ugly for improved visibility.
Sadly, Python doesn't have a simple way to flatten lists. Try this:
Which will recursively flatten a list; you can then do
If you're only going one level deep, a nested comprehension will also work:
On one line, that becomes:
A performance comparison:
Producing:
This is with Python 2.7.1 on Windows XP 32-bit, but @temoto in the comments above got
from_iterable
to be faster thanmap+extend
, so it's quite platform and input dependent.Stay away from
sum(big_list, [])