2

Could someone, please, explain why .join() behaves in the following way:

input = [1, 0, 5, 3, 4, 12, 19]
a = " ".join(str(input))
print(a)

And the result is:

[ 1 ,   0 ,   5 ,   3 ,   4 ,   1 2 ,   1 9 ]

Not only is there still a list, but also an additional space. How come? When I use map() it works:

a = " ".join(list(map(str, input)))

But I would like to know what is wrong with the .join method I'm using.

philipxy
  • 14,867
  • 6
  • 39
  • 83
habitant
  • 43
  • 3
  • There is no list and there was no list as it concerns `join()`. Before you converted the list to a string (that looks like a list when printed), and you get the a string back with the characters separated by spaces. – Klaus D. Jul 28 '22 at 16:30

2 Answers2

6

str(input) returns one string '[1, 0, 5, 3, 4, 12, 19]', so then join uses each character of the string as input (a string is an iterable, like a list), effectively adding a space between each.

The effect is more visible if we join with a -: '[-1-,- -0-,- -5-,- -3-,- -4-,- -1-2-,- -1-9-]'

In contrast, list(map(str, input)) converts each number to string, giving a list of strings (['1', '0', '5', '3', '4', '12', '19']), which join then converts to '1 0 5 3 4 12 19'

mozway
  • 194,879
  • 13
  • 39
  • 75
1

See @mozway's answer to understand .join()'s behavior.

To get what you want (using join), you should try this:

input = [1, 0, 5, 3, 4, 12, 19]
a = " ".join([str(i) for i in input])
print(a)

Output:

1 0 5 3 4 12 19
Ryan
  • 1,081
  • 6
  • 14
  • Btw, `" ".join([str(i) for i in input])` is (surprisingly) better than `" ".join(str(i) for i in input)` [due to the internal behavior of `join`](https://stackoverflow.com/questions/9060653/list-comprehension-without-in-python) ;) – mozway Jul 28 '22 at 16:23
  • @mozway Huh, interesting. Usually generators are better! Updated the post. – Ryan Jul 28 '22 at 16:24
  • Why do you think `map` is better? I think `map` vs a generator-comprehension is only a matter of style here – Mortz Jul 28 '22 at 16:24
  • [Here](https://stackoverflow.com/questions/9060653/list-comprehension-without-in-python) is a reference for the list vs generator speed in `join`. (I'll update my first comment and delete here) – mozway Jul 28 '22 at 16:26