List comprehension in if clause of another list comprehension
__peter__ at web.de
Fri Dec 19 12:45:56 CET 2008
Vedran Furac( wrote:
> In : a = 'a b c'
> In : b = 'a b, c d'
> In : [i for i in a.split() if i not in b.split()]
> Out: ['b']
> Everything ok.
> In : b.split() == [i for i in b.split()]
> Out: True
> As expected. Now, put this in the first list comprehension:
> In : [i for i in a.split() if i not in [i for i in b.split()] ]
> Out: ['d']
> Hmmmm... why is that?
>>> a = "abc"
>>> b = "a b, c d".split()
['a', 'b,', 'c', 'd']
>>> [i for i in a if i not in b]
As expected, so far, but now comes the critical step:
>>> [i for i in a if i not in [i for i in b]]
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]]
or use a generator expression which does give a new namespace:
>>> list(x for x in "abc")
['a', 'b', 'c']
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)]
More information about the Python-list