execution order in list/generator expression

Devan L devlai at gmail.com
Sun Oct 23 11:35:59 CEST 2005

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 [4]
> 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 []].

More information about the Python-list mailing list