johnfk3 johnfk3 - 3 months ago 7
Python Question

How to join two list of tuples without duplicates

I am running two queries to a database, the result i get from each, is a list of tuples which is perfect. I would like to join these into one list of tuples. These are examples of the tuples:

list1 = [('abc', 1 ), ('def', 2) ... ]
list2 = [(1000, 'abc'), (2000, 'def' ), (3000, 'def') ... ]


I want to create just one list of tuples and i join them like this:

q = []
for i in list1:
for j in list2:
if i[0] == (j[1]):
i = i + (j[0],)
q.append(i)


This returns duplicates in my new list
q
as i get something like this:

q = [('abc', 1 , 1000) , ('def', 2, 2000), ('def', 2, 2000, 3000) ...]


How can I avoid getting duplicates like the second list of tuples in the q list?
I want just
('def', 2, 2000, 3000)
and not this
('def', 2, 2000), ('def', 2, 2000, 3000)


I've been stuck on this for a while so any help is appreciated. Thanks

Answer

You don't need to append i inside the inner loop. Just once at the end of the outer loop.

q = []
for i in list1:
    for j in list2:
        if i[0] == j[1]:
            i = i + (j[0],)
    q.append(i)

There was also a typo in the outer loop. It should be list1 instead of just list.