1

my code as follows:

a_list = ['apple', 'orange', 'banana', 'this is a dog']

print('apple' in a_list)
-->>True

print('dog' in item for item in a_list)
-->><generator object <genexpr> at 0x000001E870D13F90>

Question: Why do I get the <generator object at 0x000001E870D13F90>?

How can I check, if 'dog' is in any item of this list, and the position of this item, i.e., 'dog' is in the a_list[3]?

Thanks!

msanford
  • 11,803
  • 11
  • 66
  • 93
Nina
  • 33
  • 5
  • As to "Why do I get the generator", see https://stackoverflow.com/questions/5164642/python-print-a-generator-expression . – msanford Apr 22 '21 at 18:53

3 Answers3

3

You can use enumerate to get index and item at once.

for index, value in enumerate(a_list):
    if "dog" in value:
        print(index)
Nikhil Patil
  • 173
  • 1
  • 7
2

Using the predefined list , and a standard for loop, this should give you your expected answer:

a_list = ['apple', 'orange', 'banana', 'this is a dog']
for i in a_list:
    if "dog" in i:
         print(a_list.index(i))
1

You could use any, which checks through an iterator and returns True if any of them are try, else False (contrast with all which is only True if they are all True).

print(any('dog' in item for item in a_list))
Adam Smith
  • 52,157
  • 12
  • 73
  • 112