Python Print List Without Last Element

To print a list without its last element, you can pass the result of slicing my_list[:-1] into the print() function. This slices from the first element (included) to the last element (excluded) with negative index -1 that reads like “the first sequence element from the right”.

Note that the stop index in the slicing notation [start:stop] is not included in the output of the slicing operation.

Here’s a simple example that prints the list without the last element 'Dave' using slicing:

lst = ['Alice', 'Bob', 'Carl', 'Dave']
# ['Alice', 'Bob', 'Carl']

πŸ’‘ Recommended Tutorial: An Introduction to Python Slicing

I strongly believe this slicing approach print(my_list[:-1]) is the most Pythonic, most concise, and most efficient way to solve this problem so I won’t provide any additional methods that would only be inferior.

On other websites, I have seen approaches like removing the last element from the list using pop() and printing it afterward. But this is not a great way to solve the problem because it has side effects. Also, it’s less efficient.

Another approach would be to use explicit slicing with my_list[:len(my_list)-1] but look at the unreadable code and tell me this is better!

πŸ‘‰ Related Tutorials: ‡️

Feel free to join my email academy where you’ll learn exciting new technologies in the coding space such as Blockchain engineering and Python. We have cheat sheets too!