FAQ
Hi,

I am wondering how this is evaluated.

a=(x for x in [1,2,3,4])
p=[4,5]

c=[x for x in p if x in list(a)]

c is []

but if I expand a first, like a = list(a)

c is 

So it seems that the "if" part don't get expanded ?

## Search Discussions

• at Oct 23, 2005 at 9:35 am ⇧ bonono at gmail.com wrote:
Hi,

I am wondering how this is evaluated.

a=(x for x in [1,2,3,4])
p=[4,5]

c=[x for x in p if x in list(a)]

c is []

but if I expand a first, like a = list(a)

c is 

So it seems that the "if" part don't get expanded ?
Well, for every element in p it recalculates list(a). Since the
generator is exhausted after making a list from it, it gives you
nothing afterwards. So after it checks the first element, it's
equivalent to [x for x in p if x in []].
• at Oct 23, 2005 at 9:38 am ⇧ bonono at gmail.com wrote:
Hi,

I am wondering how this is evaluated.

a=(x for x in [1,2,3,4])
p=[4,5]

c=[x for x in p if x in list(a)]

c is []
No it isn't.

In : a=(x for x in [1,2,3,4])

In : p=[4,5]

In : c=[x for x in p if x in list(a)]

In : c
Out: 

I'm willing to bet that you used up the 'a' iterator before you ran that
list comprehension, though.

In : c=[x for x in p if x in list(a)]

In : c
Out: []

Note that "x in list(a)" gets executed on each iteration, but the
iterator is used up on the first time.

In : a=(x for x in [1,2,3,4])

In : p = [4, 5, 2, 3]

In : c=[x for x in p if x in list(a)]

In : c
Out: 

--
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
• at Oct 23, 2005 at 9:48 am ⇧ Ah, no wonder. I test with p=[5,4].

thanks. so basically, I still need to expand it first given this
behaviour.

Robert Kern wrote:
bonono at gmail.com wrote:
Hi,

I am wondering how this is evaluated.

a=(x for x in [1,2,3,4])
p=[4,5]

c=[x for x in p if x in list(a)]

c is []
No it isn't.

In : a=(x for x in [1,2,3,4])

In : p=[4,5]

In : c=[x for x in p if x in list(a)]

In : c
Out: 

I'm willing to bet that you used up the 'a' iterator before you ran that
list comprehension, though.

In : c=[x for x in p if x in list(a)]

In : c
Out: []

Note that "x in list(a)" gets executed on each iteration, but the
iterator is used up on the first time.

In : a=(x for x in [1,2,3,4])

In : p = [4, 5, 2, 3]

In : c=[x for x in p if x in list(a)]

In : c
Out: 

--
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

## Related Discussions

Discussion Navigation
 view thread | post
Discussion Overview
 group python-list categories python posted Oct 23, '05 at 9:25a active Oct 23, '05 at 9:48a posts 4 users 3 website python.org

### 3 users in discussion

Content

People

Support

Translate

site design / logo © 2019 Grokbase