2

I frequently find myself writing code like this:

tupla = (1, 2, 3, 4)
if (1 in tupla) and (4 in tupla):
    ...

Is there any Pythonic way to write this more compactly, without typing tupla twice?

2 Answers 2

5
if all(x in tupla for x in list_of_x):

or

if set(list_of_x).issubset(set(tupla)):

The first one will stop as soon as the first x is not in tupla. The second one will create both sets in any case.

1
  • Now I will use the second option, but the first one will come handy when list_of_x is very long. Dec 15, 2011 at 13:27
2

What your code is asking is essentially

Is [1, 4] a subset of tupla?

You can express this question directly:

In [14]: set([1, 4]).issubset(tupla)
Out[14]: True

In [15]: set([1, 4, 7]).issubset(tupla)
Out[15]: False

or, more concisely:

In [18]: set([1, 4]) <= set(tupla)
Out[18]: True

In [19]: set([1, 4, 7]) <= set(tupla)
Out[19]: False
1
  • Thanks for the explanation. I wish I could accept multiple answers as valid. Dec 15, 2011 at 13:30

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.