How to check if value "in" some collection *and* get it?

1.1k Views Asked by At

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?

3

There are 3 best solutions below

0
Dani Mesejo On

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}
0
Tomerikoo On

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]
0
Delta On

try it:

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

if accepted_sets := [i for i in (s1, s2, s3) if value in i]:
    print(f'accepted sets: {accepted_sets}')
    print(f'first set: {accepted_sets[0]}')

output:

accepted sets: [{1, 2, 3, 4, 5}]
first set: {1, 2, 3, 4, 5}

The := defection operator

if (data := server.get_data())['condition']:
    ...
data = server.get_data()
if data['condition']:
    ...

These two codes work exactly the same. This way you do not need to request information from the server twice.