Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to use reduce() and lambda with a list containing strings

Tags:

python

lambda

I'm trying to use pythons reduce function on a list containing strings of integers.

print int("4")
\\Gives me 4 Good
print reduce(lambda x,  y: x*y,  [2, 3, 4])
\\Gives me 24 Good
print reduce(lambda x,  y: x*int(y),  ['2',  '3',  '4'])
\\Gives me 222222222222 What??

I assume that reduce is giving the lambda function something that isn't the actual string in the list? I have no idea why I'm getting 222222222222 at least, would there be an easy way to make the list an int? I guess I could just us another loop but I would still like to know whats wrong with passing the strings.

like image 996
Justin Egli Avatar asked Dec 17 '22 02:12

Justin Egli


1 Answers

>>> reduce(lambda x,  y: x*int(y),  ['2',  '3',  '4'])
'222222222222'

Okay, here is what happens:

In the first reduce step, the following calculation is done: '2' * 3. As the first operand is a string, it simply gets repeated 3 times. So you end up with '222'.

In the second reduce step, that value is multiplied by 4: '222' * 4. Again, the string is repeated four times which results in '222222222222' which is exactly the result you got.

You could avoid this by either converting x to an int as well (calling int(x)), or by mapping the list elements using an integer conversion in the first place (I actually think that’s more elegant):

>>> reduce(lambda x, y: x * y, map(int, ['2', '3', '4']))
24
like image 92
poke Avatar answered Dec 18 '22 17:12

poke