subjects = ["Math", "Physics", "Chemistry", "English"]
last_item = subjects[-1]
print(last_item)
# prints - English
Output
English
To get the last item from a list, we can use the negative indexing feature in python. Negative indexing starts from the end of the list, with -1 being the index of the last item. So, to get the last item from a list, we can use the index -1. This is a pythonic way to get the last item from the list.
Syntax
list[-1]
Code example
names = ["John", "Mohan", "Tina", "Sam", "Sonia"]
last_name = names[-1]
print(last_name)
Output
Sonia
The above code example:
If you need to get the last item in a list, one option is to use a For loop. This approach can be helpful if you need to iterate over the items in the list or if you need to access the index of the last item.
Code Example
nums = [10, 20, 30, 40, 50, 60]
total = len(nums)
for index in range(0, total):
if index == (total - 1):
print("Last item is: ", end="")
print(nums[index])
Output
Last item is: 60
The above code is iterating through the list called nums, and for each item in the list, it is checking to see if the item is the last item in the list. If it is, it prints out the item.
In Python, the list.reverse() function is used to reverse the order of the items in a list. This function can be used to get the last item in a list. To do this, the list is first reversed, and then we will get its first item using index 0.
# create a list
nums = [10, 20, 30, 40, 50, 60]
# reverse the list using list.reverse() method
nums.reverse()
# using o index get the last item
last_item = nums[0]
print(last_item)
Output
60
Explanation
nums = [10, 20, 30, 40, 50, 60] # this creates a list called nums with 6 values.
nums.reverse() # this method reverses the order of the list
last_item = nums[0] # this assigns the first item in the list to the variable last_item
print(last_item) # this prints the value of last_item
In Python, the list.pop() function is used to remove and return the last item from a list. So we can also use this function to get the last item from the list. Let's understand with with code example.
Syntax
last_item = list.pop()
Code example
# create a list
my_list = ['a', 'b', 'c', 'd', 'e']
#use lsit.pop() to get the last item
last_item = my_list.pop()
# print the last item
print("Last item is: " + last_item)
Output
Last item is: e
0 Comments