1

I am confused with Assignment Expressions (https://peps.python.org/pep-0572/). According to this question (How to find what matched in any() with Python?) I can use Assignment Expressions to find what was matched by any().

Simple example:


look = "abc"

mylist = ["abcde15", "nonono"]

if any((match := look) in s for s in mylist):
    print(f"I found {look} v {mylist}")

# I found abc v ['abcde15', 'nonono']

But how can I get abcde15 which is what I found in mylist? Thanks

vojtam
  • 1,157
  • 9
  • 34

1 Answers1

1

You're assigning match to be the value of look, which is always "abc", hence your result. Instead, you want to figure out which s in mylist was the match, which you can do by using that assignment expression on s instead:

look = "abc"

mylist = ["abcde15", "nonono"]

if any(look in (match := s) for s in mylist):
    print(f"I found {match} v {mylist}")

Which outputs

I found abcde15 v ['abcde15', 'nonono']
Tom Aarsen
  • 1,170
  • 2
  • 20