Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove space after last element in list

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading