Home > OS >  Check if value IN some collection and get it
Check if value IN some collection and get it

Time:11-05

I am thinking,

value = 3
s1 = {1,2,3,4,5}
s2 = {6,7,8,9,0}
s3 = {11,12,13,14,15}

if value in '..one of those sets..':
    '..give me that set..'

Is there an easier way to do this, apart from using if/elif ?

is there easier way to get IN which set/list/tuple

CodePudding user response:

Use next to fetch the first set that contains the value:

value = 3
s1 = {1,2,3,4,5}
s2 = {6,7,8,9,0}
s3 = {11,12,13,14,15}

found = next(s for s in (s1, s2, s3) if value in s)
print(found)

Output

{1, 2, 3, 4, 5}

CodePudding user response:

There is no real need for multiple if/elif branches. That's a non-scalable approach for testing each sequence separately. But what if you add more sequences? You will need to change the code each time.

A simpler way is packing the sequences in a tuple and iterating over all of them and checking where the value is:

for s in (s1, s2, s3):
    if value in s:
        print(s)

And this can be transformed to a list-comprehension if you expect the value to be in more than one sequence:

sequences = [s for s in (s1, s2, s3) if value in s]
  • Related