Subtle difference between any(a list) and any(a generator) with Python 3.9
ast
ast at invalid
Thu Jul 29 05:39:30 EDT 2021
Hello
Reading PEP572 about Python 3.9 assignment expressions,
I discovered a subtle difference between any(a list)
and any(a generator)
see:
>>> lines = ["azerty", "#qsdfgh", "wxcvbn"]
>>> any((comment := line).startswith('#') for line in lines)
True
>>> comment
"#qsdfgh"
>>> any([(comment := line).startswith('#') for line in lines])
True
>>> comment
'wxcvbn'
The two code snippets which seems very similar provide a
different value for "comment".
When "any" deals with a generator, it stops as soon it finds
a True value and returns True.
When "any" deals with a list, the whole list is calculated
first, and then "any" looks for a True.
Before 3.9 and the walrus operator, the two ways always provide
the same result, in a faster way with a generator.
With 3.9 and the walrus operator, result can be different
More information about the Python-list
mailing list