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








--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to