Subtle difference between any(a list) and any(a generator) with Python 3.9
Terry Reedy
tjreedy at udel.edu
Thu Jul 29 14:14:11 EDT 2021
On 7/29/2021 5:39 AM, Unknown wrote:
> 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])
Same as
>>> booleans = [(comment := line).startswith('#') for line in lines]
>>> # comment == last item.
>>> any(booleans) # Iteration though booleans stops at 1st True.
> 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.
Since the 'two ways' involve the new :=, I have no idea what 'two ways'
and 'same result' you mean before :=.
> With 3.9 and the walrus operator, result can be different
--
Terry Jan Reedy
More information about the Python-list
mailing list