Check the last item index/total values in the list in Python
Get the previous value present in the previous index by using the -1 index:
It means the last value has an index of -1 or the second last -2.
x = [5, 1, 6, 8, 3,20]
# give you the last value present in x list
print (x[-1])
Output:
20
Get the last value with the POP function
Pop function gets the last value but it also removes it from the list
x = [5, 1, 6, 8, 3,20]
print ( x.pop() ) # it remove last value which it return
print (x)
Output
20
[5, 1, 6, 8, 3]
Get the last index value then use it to get the last value
Using the len function to get the total value from it and remove -1 from it will get the last index value because the list index value starts from 0 indexes.
x = [5, 1, 6, 8, 3,20]
y =len(x)
print (y)
# for index value -1 the length output
y=y-1
# print the last value of the list with help of last index
print (x[y])
OR
x = [5, 1, 6, 8, 3,20]
print (x.__len__())
v = x.__len__() - 1
print (x[v]) # print last value in index
print (x)
Output
x = [5, 1, 6, 8, 3,20]
print (x.__len__())
v = x.__len__() - 1
print (x[v]) # print last value in index
print (x)
Output:
6
20
[5, 1, 6, 8, 3, 20]