Home > Software design >  How to remove space after last element in list
How to remove space after last element in list

Time:12-13

list = [1, 2, 3, 4]

for element in list:
    print(element, end=" ")

For this code, the output is: 1 2 3 4 . But there is a space after the last element(4).How can I remove only that last space?I tried adding sep=" " before the end=" " but it doesn't work.

CodePudding user response:

You could just use join here:

values = [1, 2, 3, 4]
output = ' '.join([str(x) for x in values])
print(output)  # 1 2 3 4

CodePudding user response:

The easiest solution would be to print everything, but the last element with space, then print the last without a space:

lst = [1, 2, 3, 4]

for i in range(len(lst) - 1):
    print(lst[i], end=" ")

print(lst[len(lst) - 1])

CodePudding user response:

You can print the first n-1 elements with space and then print the last element separately.

l = [1, 2, 3, 4]
for i in l[:-1]:
    print(i, end=" ")
print(l[-1], end="")

CodePudding user response:

This would also work.

lst = [1, 2, 3, 4]
for element in lst:
    if element == lst[len(lst)-1]:
      print(element)
    else:
      print(element, end=" ")

CodePudding user response:

The simplest way is:

print(*lst)

* operator is for unpacking, it passes individual list items to the print function like print(1, 2, 3, 4). print function use default " " space for the separator.

note: Internally print calls __str__ method of the elements, I mean it convert it to the string.

Also don't forget to not using built-in names like list.

CodePudding user response:

You can print the list by converting it into a list and then use join()

my_list = [1,2,3,4] # Don't use keywords for naming variables (it is a bad practice)
my_list = [str(x) for x in my_list]
print(' '.join(my_list))

If you want a longer solution then

my_list = [1,2,3,4]
for i in range(len(my_list)):
    if i != len(my_list)-1:
        print(str(my_list[i])   " ", end='')
    else:
        print(str(my_list[i]), end='')
  • Related