2

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

Community
  • 1
  • 1
user2256085
  • 483
  • 4
  • 15
  • 4
    You can't. You would have to do this in a for loop. – Morgan Thrapp Nov 17 '15 at 17:33
  • 1
    I'm new to python, but if you're really using 3.5, don't you need to call print as a function, like `print(x)`? I find it strange that you're seeing a NameError; should be a SyntaxError... – Frank Nov 17 '15 at 17:54
  • @Frank Is correct, Python 3 always requires brackets with `print` calls. If this is your real code and you're not getting syntax errors, you might actually be running Python 2. – SuperBiasedMan Nov 17 '15 at 17:56

4 Answers4

6

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.

Delgan
  • 18,571
  • 11
  • 90
  • 141
4

Use any when you don't care which condition is true, as long as one of them is. Instead, use a for loop (with an optional else clause if no x was in str).

for x in a:
    if x in str:
        print x
        break
else:
    print "Nothing in 'a' found in 'str'" 
chepner
  • 497,756
  • 71
  • 530
  • 681
3

Another solution:

print [x for x in a if x in str]

Useful in more complicated examples. e.g.


for

a = ['a', 'b', 'c']
str = 'a123c567b'

output will be

['a', 'b', 'c']

for

a = ['a', 'b', 'c']
str = 'a1c5c'

output will be:

['a', 'c']
Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
0
a = ['a', 'b', 'c']
string = "a123"
for i in a:
    if i in string:
        print(i)
Sergey Nosov
  • 350
  • 3
  • 10