list comprehension question

Chris Rebert clp2 at rebertia.com
Fri May 1 03:05:42 CEST 2009


On Thu, Apr 30, 2009 at 5:56 PM, Ross <ross.jett at gmail.com> wrote:
> 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?

Your comprehension is the identity comprehension (i.e. it effectively
just copies the list as-is).
What you're trying to do is difficult if not impossible to do as a
comprehension.

Here's another approach:
b = list(itertools.chain.from_iterable(a))

And without using a library function:
b = []
for pair in a:
    for item in pair:
        b.append(item)

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list