subjects = ["Math", "Physics", "Chemistry", "English"] last_item = subjects[-1] print(last_item) # prints - 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.
names = ["John", "Mohan", "Tina", "Sam", "Sonia"] last_name = names[-1] print(last_name)
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.
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])
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 print(last_item)
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 # 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.
last_item = list.pop()
# 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)
Last item is: e