Python with inconsistent result while printing, wondering what could be the reason?

Viewed 60
>>> all=[""]

>>> i="One"

>>> l=(item for item in all if item in i)

>>> print(len(list(l)))

1
>>> print(len(list(l)))

0

>>>

first time print answer is 1 without any modification second time its 0

2 Answers

It is because l it an Generator. When it stops iterator (after first time) it is empty and return len of 0.

Use [item for item in all if item in i] instead of (item for item in all if item in i) for making it a list

your l is a generator. The first time you call it with list(l) it gives you a list. The second time you call it, the generator is empty, therefore the length is 0

Related