Finding index of maximum element from Python list

Let v be a list of numbers

v = [3,5,2,4,8,6,1]

Why the following code to find the max element and its index gives an error ? (‘int’ object is not subscriptable)

reduce(lambda x,y: max(x[1],y[1]), enumerate(v))

P.S. I know there are other ways to do it, like the one below but I want to understand why the previous one does not work.

max(enumerate(v), key= lambda x: x[1])


Simeon pointed out that my code was really wrong cause lambda should have returned a tuple, not a number. Understanding this, my code could be easily fixed in the following way:

reduce(lambda x,y: x[1]<y[1] and y or x, enumerate(v))

which is, by the way, about 30% slower than

max(enumerate(v), key= lambda x: x[1])

Best answer

You’re asking why the following does not work:

reduce(lambda x,y: max(x[1],y[1]), enumerate(v))

Let’s see: your input is enumerate(v) which iterates over the following elements:

[(0, 3), (1, 5), (2, 2), (3, 4), (4, 8), (5, 6), (6, 1)]

You intend to reduce these elements with the function lambda x,y: max(x[1],y[1]). According to the docs, reduce takes a function as input that is applied to two element of the iterable. That means it reduces two elements and returns a value, which is one of the arguments of the next call to reduce.

That means x and y are tuples. For the above to work, the return value of the lambda function needs to be a tuple again because it’s used again in the next reduction. But you are returning an integer, the result of max. That’s why you’re getting an error: “‘int’ object is not subscriptable” because x[1] does not work when x is an integer.