On 20/03/06, Steve Nelson <[EMAIL PROTECTED]> 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.
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to