Each Answer to this Q is separated by one/two green lines.
I have a list of tuples that look like :
CODES = ( ('apple', 'reddelicious'), ('caramel', 'sweetsticky'), ('banana', 'yellowfruit'), )
What’s the best way to check if a value exists in that tuple? For example I want to be able to say:
'apple' in CODES
and get True
You are looking for
if any('apple' in code for code in CODES): ...
Combined with a simple generator expression, this does the task. The generator expression takes each tuple and yields
True if it is contains
any() then returns
True when the first item it requests returns
False). Hence this does what you want. It also reads nicely – if any of the tuples contain
If you are doing this a massive number of times and need performance, then it might be worth making a set of all of the values to allow you to do this very quickly:
cache = set(itertools.chain.from_iterable(CODES)))
Naturally, constructing this will be slow and use memory, so it wouldn’t be a good idea unless you need a lot of performance and will be doing a lot of membership checks.
You can use
Using it with
in will result in short-circuiting, similar to
In : CODES = ( ....: ('apple', 'reddelicious'), ....: ('caramel', 'sweetsticky'), ....: ('banana', 'yellowfruit'), ....: ) In : from itertools import chain In : 'apple' in chain(*CODES) Out: True In : 'foo' in chain(*CODES) Out: False
For performance comparisons you can check my other answer.