Main Tutorials

Python – Get the last element of a list

In Python, we can use index -1 to get the last element of a list.


#!/usr/bin/python
nums = [1, 2, 3, 4, 5]

print(nums[-1])
print(nums[-2])
print(nums[-3])
print(nums[-4])
print(nums[-5])

print(nums[0])
print(nums[1])
print(nums[2])
print(nums[3])
print(nums[4])

Output


5
4
3
2
1

1
2
3
4
5

Yet another example.


#!/usr/bin/python
# getting list of nums from the user
nums = list(map(int, input("Enter space separated numbers").split()))

# accessing the last element using -1 index
print(nums[-1])

Output


Enter space separated numbers 1 2 3 4 5
5

References

About Author

author image
I am a Pythoneer currently studying 3rd year in my Computer Science course. I will be a computer science graduate in 2 years. I am very fond of Python and Programming. I love to learn new technologies and enthusiastic about sharing my knowledge across the programming community.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments