number_list =[1,2,3]print(number_list[-1])#Gives 3
number_list[-1]=5# Set the last elementprint(number_list[-1])#Gives 5
number_list[-2]=3# Set the second to last element
number_list
[1,3,5]
# using rindex()
test_string ="abcabcabc"# using rindex() # to get last element occurrence
res = test_string.rindex('c')# printing result print("The index of last element occurrence: "+str(res))
OUTPUT:
The index of last element occurrence:8
my_list =['red','blue','green']# Get the last item with brute force using len
last_item = my_list[len(my_list)-1]# Remove the last item from the list using pop
last_item = my_list.pop()# Get the last item using negative indices *preferred & quickest method*
last_item = my_list[-1]# Get the last item using iterable unpacking*_, last_item = my_list
my_list =['red','blue','green']# Get the last item with brute force using len
last_item = my_list[len(my_list)-1]# Remove the last item from the list using pop
last_item = my_list.pop()# Get the last item using negative indices *preferred & quickest method*
last_item = my_list[-1]# Get the last item using iterable unpacking*_, last_item = my_list