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

Chris Angelico rosuav at gmail.com
Thu Jul 29 15:59:00 EDT 2021


On Fri, Jul 30, 2021 at 5:40 AM Terry Reedy <tjreedy at udel.edu> wrote:
> Since the 'two ways' involve the new :=, I have no idea what 'two ways'
> and 'same result' you mean before :=.
>

I'm not sure, but I think that a lot of people read patch notes as if
they say "this is how everyone needs to do things now", and then blame
or credit the newest features with everything that happens.

Personally, I'd search for the comments like this:

for line in lines:
    if line.startswith("#"):
        ... # whatever you do if there is one
        break
else:
    ... # whatever you do if there isn't one

But if you have to do it with a one-liner, much cleaner to use next on
your filter:

comment = next((l for l in lines if l.startswith("#")). None)

Neither of these depends on :=. I don't know what "two ways" there
are, but capturing the first element that matches a filter is a pretty
normal thing to do.

ChrisA


More information about the Python-list mailing list