xxxxxxxxxx
# To get the last element in a list you use -1 as position
bikes = ['trek', 'redline', 'giant']
bikes[-1]
# Output:
# 'giant'
xxxxxxxxxx
some_list = [1,2,3]
some_list[-1] is the shortest and most Pythonic.
#output = 3
xxxxxxxxxx
>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]
xxxxxxxxxx
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