1

I want to validate if a certain value is present within a tuple inside a list.

Now I wonder why this works:

list = [(1,2)] # tuple inside a list
# check if numbers are in tuple
if any(3 in pair for pair in list) or any(4 in pair for pair in list):
    print('Yep, found something')
else:
    print('Nope')
output: 'Nope'

And why this doesn't work:

list = [(1,2)] # tuple inside a list
# check if numbers are in tuple
if (3 in pair for pair in list) or (4 in pair for pair in list):
    print('Yep, found something')
else:
    print('Nope')
output: 'Yep, found something'

What are the mechanics at play here? Why doesn't example 2 work?

I clearly misunderstood something, but cannot find out. Can anyone explain please?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Chris
  • 21
  • 3
  • 3
    You should look at the value produced by `(3 in pair for pair in l) or (4 in pair for pair in l)`. It's not a boolean. It's a generator object because an expression like `(3 in pair for pair in l)` produces a generator. This will evaluate to `True` in this context. – Mark Aug 03 '21 at 22:59
  • Thank you! I also just read the suggested other question and the replies there answer my question. – Chris Aug 03 '21 at 23:19

0 Answers0