Search code examples
pythonlistseparator

how to remove seperator from the end of a list python


How can I remove the last separator from the end of a list?

Here's a function I created to place any separator between elements of a list.

def to_string(my_list, sep=' '):

    new_str = "List is: "

    index = 0
    for k in my_list:
        new_str = new_str + str(k) + sep
    return new_str

my_list = [1,2,3,4,5]
string = to_string(my_list, sep='-')
print(string)

Current output:

List is: 1-2-3-4-5-

What I want it to be:

List is: 1-2-3-4-5

Solution

  • Just use the join() method:

    def to_string(my_list, sep=' '):
        return "List is: " + sep.join(map(str, my_list))
    

    If you would like to use the range() function:

    for i in range(len(my_list)):
        if i > 0:
            new_str += sep
        new_str += str(my_list[i])
    

    This is unfortunately horribly un-Pythonic, and inefficient because Python has to copy into a new string for each + concatenation.