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])
Epilogue
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])
You’re asking why the following does not work:
Let’s see: your input is
enumerate(v)which iterates over the following elements: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
xandyare 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 ofmax. That’s why you’re getting an error: “‘int’ object is not subscriptable” becausex[1]does not work whenxis an integer.