Last modified: Jun 13, 2023 By Alexander Williams

3 Methods to Get Last Element of Array in Python

In Python, an array is a data structure that can store a collection of elements. In this tutorial, we'll learn how to get the last element of an array by using 3 different methods.

Method 1 : Indexing

One of the pretty simple method to get the last element of an array is Indexing. To get the last element, you can use the index -1. Here's an example:

my_array = [10, 20, 30, 40, 50] # Array

last_element = my_array[-1] # Get Last Element

print(last_element)

Output:

50

However, using the negative index -1 allows you to access the last element of the array's length easily.

Method 2: Slicing

Slicing is a Python feature that allows you to get a portion of an array. You can get the last element of an array by setting a negative index without an explicit end index.

Here is an example:

my_array = [10, 20, 30, 40, 50] # Array

last_element = my_array[-1:] # Using negative indexing

print(last_element)

Output:

[50]

As you can see, we got the result as a list.

Method 3: pop()

The pop() function removes the element at the specified position from a list. We can also use this function without specifying an index to get the last element of an array.

my_array = [10, 20, 30, 40, 50] # Array

last_element = my_array.pop() # Get Last Element

print(last_element)

Output:

50

The pop() method is called without an index, which removes and returns the last element of the list.

Conclusion

Getting the last element of an array is a common operation in Python programming. By employing indexing, slicing or the pop() method approaches, you can efficiently access the last element,