Why does string join function on a list of strings seems to exclude last item in list?

Question:

Why does last entry in list doesn’t seem to join "x " ?

a = ["apple","orange", "banana", "kiwi", "grapes", "lime"]
print("x ".join(a))
Asked By: DS_

||

Answers:

Your code outputs applex orangex bananax kiwix grapesx lime, so you may think it appends x to each one except the last one, but that is not what happen. It does put a "x " between value of the list

You could see that as adding the pattern between each, then join with an empty string

a = ["apple", "x ", "orange", "x ", "banana", "x ", "kiwi", "x ", "grapes", "x ", "lime"]
print("".join(a)) # applex orangex bananax kiwix grapesx lime

Here are easier example to understand it

print(" ".join(a)) # apple orange banana kiwi grapes lime
print("-".join(a)) # apple-orange-banana-kiwi-grapes-lime
Answered By: azro

.join() is smart in that it inserts your “joiner” in between the strings in the iterable you want to join, rather than just adding your joiner at the end of every string in the iterable. This means that if you pass an iterable of size 1, you won’t see your joiner

>>> 'b'.join(['a'])
'a'

You can use this.

[i + 'x' for i in a]
Answered By: Mohammad Sheikhian

This is because the value you specify is the separator. It is put between the list element. Since the last value doesn’t need a separator, it is not appended.
You can have a look at: https://www.w3schools.com/python/ref_string_join.asp for more information.

A workaround could be:

print(" ".join([e+"x" for e in a]))

What happens?

We use a whitespace as separator, but before we are going to put them between the list entries, we add an x to every element in your list a.
I use an inline for loop to make it in one single line. If this looks strange to you, consider this source: https://blog.teamtreehouse.com/python-single-line-loops.

Note that this means, that the whitespace is not appended to the last item if you want to achieve that, you need to move the whitespace after the x:

print("".join([e+"x " for e in a]))
Answered By: e.Fro

Not so smart but effective workaround & it avoids list comprehension.

print("x ".join(a+['']))

And if we want to get rid of the trailing space at the end

print("x ".join(a+['']).rstrip(' '))
Answered By: Rajib Lochan Sarkar
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.