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.
>>> 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With