0

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    Why `if/elif`? Just one `if` is enough: `for s in (s1, s2, s3): if value in s: return s` – Tomerikoo Nov 04 '21 at 16:17
  • The boolean version of this: [Check if a sublist contains an item](https://stackoverflow.com/q/13728023/6045800) (i.e. only return ***if*** it exists, not in which one) – Tomerikoo Nov 04 '21 at 16:24
  • @Tomerikoo As that's a slightly different use case, maybe you could post an answer with your suggested solution? Whilst `next` on a generator (the answer posted so far) would work, your approach requires less advanced prior knowledge to understand. – alani Nov 04 '21 at 16:28
  • Or, assuming `value` could be in more than one sets: `[s for s in (s1, s2, s3) if value in s]`, will return a list of all the sets containing `value` (if any). But depending on what you need, it may be better to have all the sets in a list or tuple, and return an index instead of the object itself – gimix Nov 04 '21 at 16:29
  • The "pythonic" way would be to use `try`/`except`. In other words, just try to get it and assume it's not there if an exception is raised. – martineau Nov 04 '21 at 17:02

3 Answers3

1

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}
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
0

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]
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

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.

Delta
  • 362
  • 1
  • 8