Ricardo Altamirano
Ricardo Altamirano

Reputation: 15208

Simpler/preferred way to iterate over two equal-length lists and append the max of each pair to a new list?

Given two lists of equal length, is there a simpler or preferred way to iterate over two lists of equal length and append the maximum of each pair of elements to a new list? These are the two methods I know of.

import itertools

a = [1,2,3,4,5]
b = [1,1,6,3,8]
m1 = list()
m2 = list()

for x, y in zip(a, b):
    m1.append(max(x, y))

for x in itertools.imap(max, a, b):
    m2.append(x)

Both of these result in [1, 2, 6, 4, 8], which is correct. Is there a better way?

Upvotes: 1

Views: 999

Answers (3)

John La Rooy
John La Rooy

Reputation: 304355

In Python3, map() no longer returns a list, so you should use the list comprehension or

list(map(max, a, b))

if you really need a list and not just an iterator

Upvotes: -1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799110

map(max, a, b)
[max(x, y) for x, y in zip(a, b)]

Upvotes: 7

FatalError
FatalError

Reputation: 54591

You could do it like:

a = [1,2,3,4,5]
b = [1,1,6,3,8]
m3 = [max(x,y) for (x,y) in zip(a,b)]

or even

m4 = map(max, zip(a,b))

Upvotes: 3

Related Questions