Nina
Nina

Reputation: 23

Use 'in' to check is a word is part of an item in a list

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!

Upvotes: 1

Views: 66

Answers (3)

Harsheen Rajpal
Harsheen Rajpal

Reputation: 189

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))

Upvotes: 2

Nikhil Patil
Nikhil Patil

Reputation: 203

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

for index, value in enumerate(a_list):
    if "dog" in value:
        print(index)

Upvotes: 3

Adam Smith
Adam Smith

Reputation: 54223

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))

Upvotes: 1

Related Questions