Rafael Marques
Rafael Marques

Reputation: 1445

Python - locate element in set of tuples

I have a set of tuples, each tuple has a finite number of elements.

I would like to check if there is a certain element in that set, that has the specific component i am searching for.

set_of_tuples = {(el_11, el_12, el_13), (el_21, el_22, el_23)}
a = (dont_care, el_12, dont_care)

how can i locate the tuple element in the set, that contains that specific component?

I could do this using a list comprehension, but it is a very slow proccess.

Using sets, with simple cases, i can do something like this:

el = (1,2)
set_of_tuples = {(1,2), (2,3) ...}

i can verify if it exists, doing: el in set_of_tuples.

What i asm asking, is is there is a way of doing the exact same thing, but without caring about some tuple element, for example:

el = (_,2)
el in set_of_tuples

Upvotes: 4

Views: 5973

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92904

if this Element exists in any tuple of that set

With any() function:

set_of_tuples = {(11, 12, 13), (21, 22, 23)}
el = 12
exists = any(el in t for t in set_of_tuples)

print(exists)    # True

To get the position within the outer set:

pos = -1
for i,t in enumerate(set_of_tuples):
    if el in t:
        pos = i
        break

print(pos)

Upvotes: 8

Related Questions