xxxxxxxxxx
def list_rindex(li, x):
for i in reversed(range(len(li))):
if li[i] == x:
return i
raise ValueError("{} is not in list".format(x))
xxxxxxxxxx
# To get the last element in a list you use -1 as position
bikes = ['trek', 'redline', 'giant']
bikes[-1]
# Output:
# 'giant'
xxxxxxxxxx
mylist = [0, 1, 2]
mylist[-1] = 3 # sets last element
print(myList[-1]) # prints Last element
xxxxxxxxxx
number_list = [1, 2, 3]
print(number_list[-1]) #Gives 3
number_list[-1] = 5 # Set the last element
print(number_list[-1]) #Gives 5
number_list[-2] = 3 # Set the second to last element
number_list
[1, 3, 5]
xxxxxxxxxx
# 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
xxxxxxxxxx
some_list = [1,2,3]
some_list[-1] is the shortest and most Pythonic.
#output = 3
xxxxxxxxxx
# Basic syntax:
your_list[-1]
# Example usage:
your_list = [1, 'amazing', 'list']
your_list[-1]
--> 'list'