Question

I have two lists of tuples:

a = [(4,5),(7,6),(3,2),(9,6),(25,7)]
b = [(4,6),(7,2),(6,1),(57,12)]

I want a list containing the tuples where the values of the first elements intersect.

c = [(4,5),(4,6),(7,6),(7,2)]

I tried the following code

c=[]
for i in a:
m,n=i
    for j,k in b:
        if m==j:
            i=i[:]
            i=i+(j,k)
            c=i
print c

output: (7,6,7,2)

Where am I doing wrong?

Was it helpful?

Solution

firstly, you did not update the value of c, because you equating it with i every time. Thus, the c will be replaced for every if condition is met.

secondly, i=i+(j,k) will combine two list together. for example, in your case when you equate i = (7,6) and j = 7 and k = 2, (by observation, the if-condition is met) then the i = (7,6,7,2).

I believe this will solve your problem.

a=[(4,5),(7,6),(3,2),(9,6),(25,7)]
b=[(4,6),(7,2),(6,1),(57,12)]
c=[]
for i in a:
m,n=i
for j,k in b:
    if m==j:
        c.append(i)
        break

for i in b:
m,n=i
for j,k in a:
    if m==j:
        c.append(i)
        break

print (c)

OTHER TIPS

Although this is a bad question since your question is not very clear, I will try to give my understanding of what you actually want.

So you want to iterate through both list, and if there is an element in a with the same first tuple-element in b at the same position, then put both of them in the list c.

Then this is what you want:

for el_a, el_b in zip(a,b):
    if el_a[0]==el_b[0]:
        c.append(el_a)
        c.append(el_b)

The problem with your code is that i=i+(j,k) will combine the tuple into longer tuple, in your case, it's combining (7,6) with (7,2), which becomes (7,6,7,2). You don't need this step.

The second problem is that, to add element into a list, you need to do c.append(element), not c=i like you're doing right now.

You can try this with the module itertools

import itertools
list(itertools.chain(*[e for e in zip(a,b) if e[0][0] == e[1][0]]))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top