0

I have a list:

mylist = ['item 101', 'element 202', 'string 303', 'member 404']

I want to identify the three digits associated with 'item', but 'item' is not always in the same position, so I cannot use mylist[0].

I looked at the accepted answer in this StackOverflow post, and tried the following:

if any('item' in s for s in mylist):
    print(s)

I get the following error:

NameError: name 's' is not defined

In researched that error, but I haven't been able to find any examples/solutions that fit this particular situation.

Community
  • 1
  • 1
rwjones
  • 377
  • 1
  • 5
  • 13
  • 1
    The reason you are getting this error is because `s` is only in scope for the life of that generator expression. Once it is exhausted and `any()` returns it's value `s` will no longer be available. – kylieCatt Jun 02 '15 at 14:28

4 Answers4

3

The simpler way to approach your problem is by using a list comprehension

>>> mylist = ['item 101', 'element 202', 'string 303', 'member 404']
>>> [s for s in mylist if 'item' in s]
['item 101']

If you are assured that there is only one element like that in the list then you can aswell use list-indexes

>>> [s for s in mylist if 'item' in s][0]
'item 101'

Or a better way would be to use next and a gen-exp.

>>> next(s for s in mylist if 'item' in s)
'item 101'

And to get the 3 digits from the string 'item 101' you can do mystr[5:9] where mystr has the value 'item 101'

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
1

s only exists in the scope of the single statement:

'item' in s for s in mylist

If you want to find all items you'll have to save them first into a list. I'm not sure if you want the index of each item or the text of each item or what but you could do:

mylist = ['item 101', 'element 202', 'string 303', 'member 404']
items = [s for s in mylist if 'item' in s]
if any(items):
    print items[0]
Brett
  • 256
  • 1
  • 8
1

I have tried the answer in your linked post too, and have run into the same problem. However, if you use a proper comprehension to create a list of booleans, it should work:

>>> mylist = ['item 101', 'element 202', 'string 303', 'member 404']
>>> if any(['item' in s for s in mylist]):
...     print 'Found item'

prints out what is expected.

wonderb0lt
  • 2,035
  • 1
  • 23
  • 37
1

That error is happening because you are trying to look into s before s has been defined in the for loop. A simple work around for that would be to break the statements apart into:

for s in mylist: if 'item' in s: print(s)