list comprehension question

J Kenneth King james at agentultra.com
Fri May 1 10:31:45 EDT 2009


Chris Rebert <clp2 at rebertia.com> writes:

> 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)

This is much more clear than a nested comprehension.

I love comprehensions, but abusing them can lead to really dense and
difficult to read code.



More information about the Python-list mailing list