VincFort
VincFort

Reputation: 1180

How to check if multiple characters are in a list?

I have a list of combinations (say 5 digit pin number) and want to take only the ones that have 1,2 and 3 in them. Looked around here but didnt seem to find any for some reason.

if 1 in combination and 2 in combination and 3 in combination:

This seems to work, but I'm sure there is a more efficient way since mine is quite ugly.

Upvotes: 3

Views: 1346

Answers (2)

Neel
Neel

Reputation: 21243

You can convert your mobination to string, and check the intersaction in set.

>>> combination = '456'
>>> needed = '123'
>>> set(needed) & set(combination)
set([])
>>> combination = '156'
>>> set(needed) & set(combination)
set(['1'])

If you get value return from intersection then your needed value is in combination.

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361605

If combination is a set you can perform a subset check:

if {1, 2, 3} <= combination:

Otherwise, you can do:

if all(x in combination for x in (1, 2, 3)):

Upvotes: 5

Related Questions