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

No comments yet. Be the first to leave a comment!

Leave a Comment

Your email address will not be published. Required fields are marked *