0
how to compare list and find max numbers
l1=[1, 3, 9, 7] l2=[2, 4, 6, 8] how to compare list and find max numbers the output will be [2,4,9,8]
7 Answers
+ 2
l1=[1, 3, 9, 7]
l2=[2, 4, 6, 8]
nl=[]
for x in range(len(l1)):
if l1[x]>l2[x]: nl.append(l1[x])
else: nl.append(l2[x])
print(nl)
+ 2
THANKS, SAN UNDERSTOOD I HAVE TRIED THIS
for i in zip(l1,l2):
new_list.append(max(i))
print(new_list)
hey, Shadoff thanks you also it will be better if you provide code :)
+ 1
You have to iterate through each item of each list and get max value, and this value append to another list
+ 1
Here's a couple other options
l1=[1, 3, 9, 7]
l2=[2, 4, 6, 8]
l3 = [max(x) for x in zip(l1, l2)]
print(l3)
l4 = list(map(max, zip(l1, l2)))
print(l4)
0
Hey chaotic Dawg
Can you please explain me l4 statement
0
Amol Bhandekar
l4 works similar to l3
The zip() function will create a zip object where each element from the same index of each list is put into a tuple of those elements. It would look much like this as a list;
[(1,2),(3,4),(9,6),(7,8)]
The map() will then pass each element from the zip object into the max() function, resulting in the corresponding map object that is then converted to the final list that is output.