Reputation: 41
I have 2 lists with elements like:
list1=[2,54,31,6,42]
list2=[4,98,43,3,2]
I want a def that compares the numbers and returns a 3rd list with the biggest one.
In this example the 3rd list would be:
list3=[4,98,43,6,42]
Upvotes: 3
Views: 7362
Reputation: 5704
Here's a simple def
/function to zip()
the two lists and then get max()
and store it into a new list3 and returned:
list1=[2,54,31,6,42]
list2=[4,98,43,3,2]
def function(list1,list2): #def returns 3rd list
list3 = [max(value) for value in zip(list1, list2)]
return list3
print(function(list1,list2)) # call def named function to print
Output:
[4, 98, 43, 6, 42]
Upvotes: 1
Reputation: 107287
Use map()
function:
In [4]: list(map(max, list1, list2))
Out[4]: [4, 98, 43, 6, 42]
Upvotes: 12
Reputation: 11134
You can use list comprehension with max
function.
>>> list1=[2,54,31,6,42];list2=[4,98,43,3,2]
>>> [max(i) for i in zip(list1,list2)]
[4, 98, 43, 6, 42]
>>>
Upvotes: 6