Reputation: 355
I am new to python so apologies for the naive question. I have a list
l1 = [2, 4, 6, 7, 8]
and another list of tuples
l2 = [(4,6), (6,8), (8,10)]
I want to output a list l3
of size l1
that compares the value of l1
to the first co-ordinates of l2
and stores the second co-ordinate if the first co-ordinate is found in l1
, else stores 0.
output :
l3 = [0, 6, 8, 0, 10]
I tired to do a for loop like:
l3 = []
for i in range(len(l1)):
if l1[i] == l2[i][0]:
l3.append(l2[i][1])
else:
l3.append(0)
but this doesn't work. It gives the error
IndexError: list index out of range
which is obvious as l2
is shorter than l1
.
Upvotes: 11
Views: 226
Reputation: 4795
I would always use Ajax1234's solution instead, but I wanted to illustrate how I would approach it using a for-loop, as you intended:
l3 = []
for elem in l1:
pairs = list(filter(lambda x: x[0] == elem, l2))
l3.append(pairs[0][1] if pairs else 0)
An alternate approach would be using next()
and a list comprehension instead of filter()
and a for-loop. This one is far more efficient and readable:
l3 = [next((u[1] for u in l2 if u[0] == elem), 0) for elem in l1]
Upvotes: 1
Reputation: 71451
You can create a dictionary from l2
:
l1 = [2,4,6,7,8]
l2 =[(4,6),(6,8),(8,10)]
new_l2 = dict(l2)
l3 = [new_l2.get(i, 0) for i in l1]
Output:
l3 = [0,6,8,0,10]
Upvotes: 11