How to Slice the Last n Elements in Python?

Estimated read time 1 min read

To slice the last n elements in a list or array in Python, you can use negative indexing. Here’s an example:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

last_n_elements = my_list[-4:]

print(last_n_elements)

In this example, we define a list my_list containing 10 elements.

We use negative indexing to access the last 4 elements of the list. The expression my_list[-4:] returns a new list containing the last 4 elements of my_list.

Finally, we print the new list last_n_elements.

Note: The [-n:] slice notation selects the last n elements of the list. If you want to select a range of elements starting from the second to last element, you can use my_list[-2:-n-2:-1], where n is the number of elements you want to select. This selects a range of n elements starting from the second to last element and working backwards.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply