Milan Panic
Milan Panic

Reputation: 503

Finding a string in list of strings in python is not working for me

I have written a more complex program on python, but I'm stuck on trying to find out if a list contains a given string.

Simplified problem:

product_names = ['string1', 'string2']
products = [{'id': 'string1', 'test': 'test1 - value'}, {'id': 'string3', 'test': 'test2 - value'}]

# prints: string1 string3
product_ids = (p['id'] for p in products)
for ids in product_ids:
    print(ids)

# doesn't print found
for p in product_names:
    if p in product_ids:
        print('found')
        
# doesn't print missing product names
if not all(p in product_ids for p in product_names):
    print('missing product names')

I don't get why this doesn't work, do I have to restart the starting index somehow, and is so, how?

Upvotes: 0

Views: 54

Answers (1)

Mattias
Mattias

Reputation: 66

Change

product_ids = (p['id'] for p in products)

to

product_ids = [p['id'] for p in products]

and it should work.

What you have done is created a generator which will be exhausted after your first for loop. Changing to square brackets instead creates a list which can be iterated over as many times as you want.

Upvotes: 5

Related Questions