theMobDog - 1 year ago 76
Python Question

# Python: from list to enumerated list to pass to lambda reduce function

I am trying to pass a list of hex char, into a lambda function, reduce to calculate a total decimal value. I am not sure what I am doing wrong but the python interpreter wouldn't recognize list(enumerate(reversed(numList)) as a list of tuples.

``````  numList =  ['3', '0', 'e', 'f', 'e', '1']
reduce(lambda sum,(up,x):sum+ int(x,16)*16**up,
enumerate(reversed(numList)))
``````

when I print out

``````  list(enumerate(reversed(numList))
``````

It is a list of tuples.

``````  [(0, '1'), (1, 'e'), (2, 'f'), (3, 'e'), (4, '0'), (5, '3')]
``````

But it spit our error: can only concatenate tuple (not "int") to tuple

UPDATE:

The code is now working with a minor addition ",0" added to the lambda

``````    reduce(lambda sum,(up,x):sum+ int(x,16)*16**up,
list(enumerate(reversed(numList))),0)
``````

I don't understand what that means. Also I am not sure what is the best way to approach this.

that means you make sure, that it starts with 0 instead of the first Argument - in this case (0,'1') - because otherwise the types dont match? – am2 1 min ago

.

the third argument you add is initializer. without it, the sum in first iteration will be (0,'1'). so you were trying to evaluate (0,'1')+int(x,16)*16**up which is invalid. – ymonad 14 mins ago

UPDATE 2:

``````reduce(lambda sum,(up,x):sum+ int(x,16)*16**up,enumerate(reversed(numList)),0)
``````

is just as good and
`enumerate()`
returns iter and
`list(enumerate...)`
is redundant.

Marked it as solved.

You don't need to use the generic `reduce` function when all you really need is to calculate the sum.
``````sum( int(x,16)*16**up for up,x in enumerate(reversed(numList)) )
``````int(''.join(numList), 16)