Subtle difference between any(a list) and any(a generator) with Python 3.9

Chris Angelico rosuav at gmail.com
Thu Jul 29 05:59:30 EDT 2021


On Thu, Jul 29, 2021 at 7:49 PM ast <ast at invalid> 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])
> True
>  >>> comment
> 'wxcvbn'

"any" is irrelevant here. What you're seeing is that a list
comprehension is evaluated fully, and a generator expression isn't.
That's exactly what they're meant to do :)

ChrisA


More information about the Python-list mailing list