Python List – Slice all but last element

Python List – Slice all but last element

To slice all elements from a given list but excluding the last element in Python, you can use either slice the list from starting to length of the list minus one, or use a negative index of -1 for the stop index.

If you are using a positive index for slicing the list to exclude the last element, you can use the following syntax.

my_list[: len(my_list)-1]

Or, if you are using a negative index for slicing the list to exclude the last element, you can use the following syntax.

my_list[: -1]

Examples

In the following examples, we shall go through use cases of slicing the list without the last element, using positive index approach, or negative index approach in the slicing expression.

1. Slice the list without last element in Python, using positive index

In this example, we are given a list in my_list with six elements. We have to slice this list such that the last element in it is excluded.

Use the regular slicing expression with default start position, and length of list minus one as the stop position.

Python Program

# Given list
my_list = [10, 20, 30, 40, 50, 60]

# Slice the list, without last element
sliced_list = my_list[: len(my_list)-1]

# Print sliced list
print(sliced_list)
Run Code Copy

Output

[10, 20, 30, 40, 50]

2. Slice the list without last element in Python, using negative index

In this example, use negative index to slice the given list without last element.

Use the slicing expression with default start position, and minus one as the stop position.

Python Program

# Given list
my_list = [10, 20, 30, 40, 50, 60]

# Slice the list, exclude last element
sliced_list = my_list[: -1]

# Print sliced list
print(sliced_list)
Run Code Copy

Output

[10, 20, 30, 40, 50]

Summary

In this Python lists tutorial, we have seen how to slice all elements of a given list but without the last element, using positive or negative indices with slicing. Also, we have seen examples for each of the approaches.

Related Tutorials

Code copied to clipboard successfully 👍