List comprehension in if clause of another list comprehension

Vedran Furac( vedranf at vedranf.mine.nu
Fri Dec 19 06:57:35 EST 2008


Peter Otten wrote:

> The problem is that list comprehensions do not introduce a new namespace. So
> the inner and the outer list comp share the same i. You can either rename
> the inner i
> 
>>>> [i for i in a if i not in [k for k in b]]
> ['b']
> 
> or use a generator expression which does give a new namespace:
> 
>>>> list(x for x in "abc")
> ['a', 'b', 'c']
>>>> x
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name 'x' is not defined
> 
>>>> [i for i in a if i not in (i for i in b)]
> ['b']

Thanks!



More information about the Python-list mailing list