[Tutor] Alternative to nested loops

John Fouhy john at fouhy.net
Sun Mar 19 23:41:59 CET 2006


On 20/03/06, Steve Nelson <sanelson at gmail.com> wrote:
> Hi All,
>
> I had a feeling I could do this:
>
> >>> foo
> [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
> >>> for c in foo:
> ...     for b in c:
> ...             print b

What you're doing is called "flattening" a list.  You can do it with a
list comprehension:

>>> foo = [[1,2,3], [4,5,6], [7,8,9]]
>>> [x for y in foo for x in y]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

There are also other ways; ActiveState has several in its cookbook.

If you want to sum, you could also use a generator expression
(requires Python 2.4):

>>> sum(x for y in foo for x in y)
45

This will be slightly faster, depending on how big your list is.

But really, there are times when clarity and efficiency both come
together and say "Write explicit for loops" :-)

--
John.


More information about the Tutor mailing list