list() strange behaviour
jak
nospam at please.ty
Sun Jan 24 04:49:34 EST 2021
Il 20/12/2020 21:00, danilob ha scritto:
> Hi,
> I'm an absolute beginner in Python (and in English too ;-)
> Running this code:
>
>
> --------------
> # Python 3.9.0
>
> a = [[1, 2, 0, 3, 0],
> [0, 4, 5, 0, 6],
> [7, 0, 8, 0, 9],
> [2, 3, 0, 0, 1],
> [0, 0, 1, 8, 0]]
>
>
> b = ((x[0] for x in a))
>
> print(list(b))
> print(list(b))
> ---------------
>
>
> I get this output:
>
> [1, 0, 7, 2, 0]
> []
>
>
> I don't know why the second print() output shows an empty list.
> Is it possible that the first print() call might have changed the value
> of "b"?
>
> Thank you in advance.
You should see a generator as a container emptying while you are reading
it, so you should recreate it every time:
################################
# Python 3.9.0
a = [[1, 2, 0, 3, 0],
[0, 4, 5, 0, 6],
[7, 0, 8, 0, 9],
[2, 3, 0, 0, 1],
[0, 0, 1, 8, 0]]
b = lambda : (x[0] for x in a)
print(list(b()))
print(list(b()))
output:
[1, 0, 7, 2, 0]
[1, 0, 7, 2, 0]
################################
More information about the Python-list
mailing list