Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Python map function + range

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?

like image 501
Pierre B Avatar asked Dec 05 '22 00:12

Pierre B


2 Answers

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)))
like image 149
Martijn Pieters Avatar answered Dec 06 '22 13:12

Martijn Pieters


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"]
like image 41
Simon Kirsten Avatar answered Dec 06 '22 13:12

Simon Kirsten