list comprehension question

thor yaksavage at gmail.com
Fri May 1 03:26:46 EDT 2009


On May 1, 2:28 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:
> Ross <ross.j... at gmail.com> writes:
> > If I have a list of tuples a = [(1,2), (3,4), (5,6)], and I want to
> > return a new list of each individual element in these tuples, I can do
> > it with a nested for loop but when I try to do it using the list
> > comprehension b = [j for j in i for i in a], my output is b =
> > [5,5,5,6,6,6] instead of the correct b = [1,2,3,4,5,6]. What am I
> > doing wrong?
>
> When writing nested list comprehension, the for loops are in the same
> order as you would write a normal nested for loop (which is not
> necessarily intuitive when you first find out but is very handy in the
> long run I think).
>
> So write:
>
>     [j for i in a for j in i]
>
> --
> Arnaud
an trick
>>> a
[(1, 2), (3, 4), (5, 6)]
>>> sum(a, ())
(1, 2, 3, 4, 5, 6)
>>>
you may search the maillist , somebody questioned before



More information about the Python-list mailing list