5

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?

Pierre B
  • 654
  • 2
  • 6
  • 15

2 Answers2

18

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)))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

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"]
Community
  • 1
  • 1
Simon Kirsten
  • 2,542
  • 18
  • 21