Appending elements of a list of tuples if a condition is met

I am very new in Python and coding in general, so this question may sound dumb.

I have lists of tuples (as seen below).
The output I am looking for is to have: list2= [(‘a’,4), (‘b’,2)]

That is, if the tuples’ first elements in list1 are also in the tuples’ first elements of listx, append to the empty list2 tuples with the first and second elements of list1’s tuples.

But I got an empty list2 instead. What am I doing wrong?

> listx= [('a',55), ('b',101)]
> list1= [('a',4),('b',2), ('c',1), ('d',2)]
> list2= []
> for i,n in list1:
>     if i in listx:
>         list2.append((i,n))
>         print(list2)

When you write i in listx, you’re actually asking whether i == listx[0], i == listx[1], etc.

1 Like