I'm trying to understand the difference between these lines of code:
list(''.join(map(lambda x: str(x * 3), range(1, 4))))
Out: ['3', '6', '9']
as expected.
However:
list(''.join(map(lambda x: str(x * 5), range(1, 4))))
outputs ['5', '1', '0', '1', '5']
, while I expected: ['5','10','15']
In the same way that
[x for x in map(lambda x: str(x * 5), range(1, 4))]
ouputs ['5','10','15']
.
What's wrong here?
You first joined all strings together into one big string, and then converted that string to a list, which always results in all the individual characters being pulled out as elements:
>>> list(map(lambda x: str(x * 5), range(1, 4)))
['5', '10', '15']
>>> ''.join(map(lambda x: str(x * 5), range(1, 4)))
'51015'
>>> list(''.join(map(lambda x: str(x * 5), range(1, 4))))
['5', '1', '0', '1', '5']
As you can see above, all you need to do is remove the str.join()
call, just use list()
directly on map()
:
list(map(lambda x: str(x * 5), range(1, 4)))
All numbers in the first snippet are single digit numbers, so joining them and splitting them won't make a difference. See Martijn Pieters answer. In the second it will make a difference because some are two digit numbers.
Example:
[3, 6, 9] join -> 369 split -> ["3", "6", "9"]
[5, 10, 15] join -> 51015 split -> ["5", "1", "0", "1", "5"]
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