Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if any(x in str for x in a): what's x when true

Tags:

python

This post gets me half way to where I want to go. I'd like to know which string the following code found, but on my machine it isn't working:

a = ['a', 'b', 'c']
str = "a123"
if any(x in str for x in a):
    print x 

This produces the error: "NameError: name 'x' is not defined". How does one determine which string (within a) was found? In other words, based on which string was found in the list, I want to do something specific in the code that follows, thus I need to know what x was when the condition was true. I'm using python 3.5.0

like image 601
user2256085 Avatar asked Jan 18 '26 22:01

user2256085


1 Answers

The variable x refers to the scope of the generator passed to the any() function, so you can not print x outside of this generator.

any() just returns True or False.

Instead, you might use next():

print next(x for x in a if x in str)

And add a default value in the case no correct value is found:

s = next((x for x in a if x in str), None)
if s:
    print s

Just a note: you should not create a variable which is called str because there is a built-in with the same name. This is considred as bad practice to overwrite it because this can lead to confusion.

like image 193
Delgan Avatar answered Jan 20 '26 12:01

Delgan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!