Natalia Resende
Natalia Resende

Reputation: 195

how to iterate through a list of tuples and compare elements?

I have a list of tuples such as

list_tuples = [(2,3), (4,7), (3,2), (7,8), (7,4)]

I want to find the tuples in this list whose elements are the same but reversed order. in this case my output would be:

new_list_tuples = [(2,3), (3,2), (4,7), (7,4)]

I've tried the below code but apparently it doesn't work because it doesn't make sense:

for i in lista:
    if i[0] == i[1] and i[1] == i[0]:
        print(i)

can anyone help me with this? Many thanks in advance!

Upvotes: 1

Views: 1222

Answers (3)

RIAM KIM
RIAM KIM

Reputation: 21

Main idea is divide tuple into two section front number, and back number.

If front_numbers[X] == Back_number[Y] and front_number[Y] == Back_number[X]. It means list_tuples[X] and list_tuples[Y] have same element but opposite sequence.

list_tuples = [(2,3), (4,7), (3,2), (7,8), (7,4)]

front_number = []
back_number = []

for i in range(len(list_tuples)):
    front_number.append(list_tuples[i][0])
    back_number.append(list_tuples[i][1])

new_list_tuple = []

for i, v in enumerate(front_number):
    for b_i, b_v in enumerate(back_number):
        if b_i == i:
            pass
        elif v == b_v:
            if front_number[b_i] == back_number[i]:
                if (front_number[i], back_number[i]) not in new_list_tuple:
                    new_list_tuple.append((front_number[i],back_number[i]))

Upvotes: 0

user13561317
user13561317

Reputation:

What i can think of is you can use nested for loop

new_list_tuple=[(2,3), (3,2), (4,7), (7,4)]
convert_list=[]
for i in range(len(new_list_tuple)):
    for j in range(i,len(new_list_tuple)):
        if new_list_tuple[i]==new_list_tuple[j][::-1]:
            convert_list.extend([new_list_tuple[i],new_list_tuple[j]])
print(convert_list)

Upvotes: 0

Selcuk
Selcuk

Reputation: 59333

You can use a list comprehension:

>>> [t for t in list_tuples if (t[1], t[0]) in list_tuples]
[(2, 3), (4, 7), (3, 2), (7, 4)]

That being said, using a set for lookups is faster:

>>> set_tuples = set(list_tuples)
>>> [t for t in list_tuples if (t[1], t[0]) in set_tuples]
[(2, 3), (4, 7), (3, 2), (7, 4)]

Upvotes: 3

Related Questions