list() strange behaviour

Tim Chase python.list at tim.thechases.com
Sun Dec 20 15:38:47 EST 2020


On 2020-12-20 21:00, danilob wrote:
> b = ((x[0] for x in a))

here you create a generator

> print(list(b))
> [1, 0, 7, 2, 0]

and then you consume all the things it generates here which means
that when you go to do this a second time

> print(list(b))

the generator is already empty/exhausted so there's nothing more to
yield, giving you the empty result that you got:

> []


If you want to do this, convert it to a list once:

 >>> c = list(b)

or use a list-comprehension instead creating a generator

 >>> c = [x[0] for x in a]

and then print that resulting list:

 >>> print(c)
 >>> print(c)

-tkc





More information about the Python-list mailing list