Computer >> Computer tutorials >  >> Programming >> Python

Python How to get the last element of list


In this tutorial, we are going to see different ways to get the last element from the list. Let's see one by one.

Index

We can get the last element of the list using the index. And we can get the index of the last element by the length of the list. Let's see the code.

Example

# initializing the list
numbers = [1, 2, 3, 4, 5]
# printing the last element
print(f"Last element:- {numbers[len(numbers) - 1]}")

Output

If you execute the above program, then you will get the following result.

Last element:- 5

Negative Index

We can get the last element of the list using negative indexing. And the negative indexing from -1. Let's see the code.

Example

# initializing the list
numbers = [1, 2, 3, 4, 5]
# printing the last element
print(f"Last element:- {numbers[-1]}")

Output

If you execute the above program, then you will get the following result.

Last element:- 5

Pop

We can get the last element of the list by popping it out. The pop method of the list removes returns the last element from the list. Let's the code.

Example

# initializing the list
numbers = [1, 2, 3, 4, 5]
# printing the last element
print(f"Last element:- {numbers.pop()}")

Output

If you execute the above program, then you will get the following result.

Last element:- 5

Conclusion

If you have any doubts regarding the tutorial, mention them in the comment section.