10

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 ?

maxhb
  • 8,554
  • 9
  • 29
  • 53
hsm
  • 139
  • 1
  • 3
  • 5
    How have you tried to do it, and what's going wrong? – jonrsharpe Feb 06 '16 at 18:30
  • Input? Or Output? How about the example code that you've tried and the reason it does not work for you?? – Vorsprung Feb 06 '16 at 18:32
  • I'll start you out with [How can I iterate through two lists in parallel in Python?](http://stackoverflow.com/q/1663807). Add a [list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) and the `max()` function and you'll have a solution in just one line. – Martijn Pieters Feb 06 '16 at 18:34

5 Answers5

10

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)]
lejlot
  • 64,777
  • 8
  • 131
  • 164
6

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])
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
1

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]

Pouria
  • 1,081
  • 9
  • 24
1
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]

AJH
  • 799
  • 1
  • 3
  • 16
-1

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)
Alok Prasad
  • 622
  • 7
  • 12