Avin Bhagwani
Avin Bhagwani

Reputation: 17

What's the difference between these codes? Why do they have different outputs?

list = ['first', 'second', 'third', 'fourth']
s = '/'
newList = s.join(list)
print(newList)

This code outputs

"first/second/third/fourth"

list = ['first', 'second', 'third', 'fourth']
s = '/'
newList = s.join(str(list))
print(newList)

This code outputs

 "[/'/f/i/r/s/t/'/,/ /'/s/e/c/o/n/d/'/,/ /'/t/h/i/r/d/'/,/ /'/f/o/u/r/t/h/'/]"

What does str() do here that causes the list to separate by every letter?

Upvotes: 0

Views: 80

Answers (3)

Mad Physicist
Mad Physicist

Reputation: 114548

str converts it's argument to its string representation. The string representation of a list is a single string starting with an opening square bracket and ending with a closing one. The elements in between are converted using repr and separated by ,. That string is in itself an iterable of characters. As such, join will place a / between each element of the iterable, i.e., between every character of the string.

The equivalent to your first code would be to convert every string element of the list into a separate string:

s.join(str(x) for x in list)

In your particular case, str is a no-op because it will return the argument if the input is already a str.

For arbitrary lists, the approach shown here is better than just using s.join(list), because join requires all the elements of the iterable to be strs, but makes no attempt to convert them, as say print would. Instead, it raises a TypeError when it encounters a non-str.

Another, less pythonic, but nevertheless very common, way of expressing the same conversion is

s.join(map(str, list))

And of course, the insert the mandatory admonition against naming variables after common builtins here for yourself.

Upvotes: 1

Jay
Jay

Reputation: 24905

The join function is a string method which returns a string concatentated with the elements of a iterable.

Now, in the first case:

list_1 = ['first', 'second', 'third', 'fourth'] #I changed the name to list_1 as list is a keyword
s = '/'
newList = s.join(list_1)
print(newList)

Every string in the list is a iterable, so, join outputs by concatenating all elements of the list by adding '/' between each element.

In the second case:

list_1 = ['first', 'second', 'third', 'fourth']
s = '/'
newList = s.join(str(list_1))
print(newList)

Since, str converts the entire list including the [ and ] braces as a string. Due to this every character in the new string becomes a iterable and join returns a new string by adding '/' between every element.

Upvotes: 1

Ming
Ming

Reputation: 358

The str() create a string like "['first', 'second', 'third', 'fourth']".

And s.join() treat the string as a char array. Then it put '/' between every element in the array.

Upvotes: 3

Related Questions