0

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?

3
  • 4
    product_ids is a generator; you can't use in on it. Use [p['id'] for p in products] instead of (p['id'] for p in products) to make it a list instead. Commented Dec 10, 2020 at 13:51
  • product_ids = (p['id'] for p in products) --> product_ids = [p['id'] for p in products] Commented Dec 10, 2020 at 13:52
  • Yeah, that is the solution, thank you :) Commented Dec 10, 2020 at 14:02

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.