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
.
The major difference between tuples and lists is that a list is mutable, whereas a tuple is immutable. This means that a list can be changed, but a tuple cannot.
List and Tuple in Python are the classes of Python Data Structures. The list is dynamic, whereas the tuple has static characteristics. This means that lists can be modified whereas tuples cannot be modified, the tuple is faster than the list because of static in nature.
We can use the Python map() function along with functools. reduce() function to compare the data items of two lists. The map() method accepts a function and an iterable such as list, tuple, string, etc. as arguments.
Comparing lists in Python The set() function creates an object that is a set object. The cmp() function is used to compare two elements or lists and return a value based on the arguments passed. In the following sections, we will see the application of set() , cmp() , and difference() functions.
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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With