'Finding the index wise maximum values of two lists

Lets say I have 2 lists:

L1 = [2,4,1,6]
L2 = [1,5,2,3]

The output should be a new list that contains the biggest numbers found in L1 or L2 based on their position.

Example output:

L3 = [2, 5, 2, 6]

How to do it ?



Solution 1:[1]

One of the possible solutions is to zip your lists, and then applying max operation element-wise, which can be obtained in python through call to functional map

L1 = [2,4,1,6]
L2 = [1,5,2,3]
L3 = map(max, zip(L1, L2)) # python2
L3 = list(map(max, zip(L1, L2))) # python3

or more pythonic through list comprehensions

L3 = [max(l1, l2) for l1, l2 in zip(L1, L2)]

or a bit shorter version using unpacking operation

L3 = [max(*l) for l in zip(L1, L2)]

Solution 2:[2]

You could use zip() and max() in a list comprehension:

>>> L1 = [2,4,1,6]
>>> L2 = [1,5,2,3]
>>> [*map(max, zip(L1, L2))]
[2, 5, 2, 6]

If you can use numpy, it's very simple with the numpy.maximum() ufunc:

>>> import numpy as np
>>> arr1 = np.array([2, 4, 1, 6])
>>> arr2 = np.array([1, 5, 2, 3])
>>> np.maximum(arr1, arr2)
array([2, 5, 2, 6])

Solution 3:[3]

Here is a quick fix, in one set of iterations!

list_a = [2,4,1,6]
list_b = [1,5,2,3]

max_list = [value if list_b[index]<value else list_b[index] for index, value in enumerate(list_a)]

print(max_list)

Displays: [2, 5, 2, 6]

Solution 4:[4]

a, b = [10,20,30], [11,2,40]
c = [x if x > y else y for x, y in zip(a, b)]
print(c)

Output: [11,20,40]

Solution 5:[5]

Using List comprehension

l=[1,2,7]
m=[4,5,6]

max=[(l[i] if l[i]>m[i]  else m[i] ) for i in range(0,len(l))]
print(max)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lejlot
Solution 2
Solution 3
Solution 4 AJH
Solution 5 Alok Prasad