how to iterate all sub-element in a list

Rustom Mody rustompmody at gmail.com
Fri Jan 31 07:12:11 EST 2014


On Friday, January 31, 2014 4:18:13 PM UTC+5:30, Peter Otten wrote:
> seaspeak wrote:

> > a list like L = [[1, 2], [3, 4, 5], [6]], which has
> > random numbers of list, which has random numbers.
> > How do I get another list m = [1, 2, 3, 4, 5, 6] in a succinct way? ( or
> > iterate them) I should provide my own solution, but I really can't come
> > out with one.

> sum(L, [])
> list(itertools.chain.from_iterable(L))

> but as a learning experience you should do this at least once with two 
> nested for loops, then again with a single for loop and list.extend().

And then again with a double comprehension:
[y for x in L for y in x]




More information about the Python-list mailing list