Python Program to Get the Last Element of the List – 2024

Hey guys, in this blog we will see a Python Program to Get the Last Element of the List.

Table of Contents

Using negative indexing

my_list = ['a', 'b', 'c', 'd', 'e', 'f']

# print the last element
print(my_list[-1])

Output

f
  • While indexing lists we use indices like 0,1,2,3,etc. but when we want to start indexing the list from the last, we use negative indices like -1, -2,-3,etc.
  • In the above case:

my_list[-1] = f
my_list[-2] = e
my_list[-3] = d
my_list[-4] = c
my_list[-5] = b

Using positive indexing

my_list = ['a', 'b', 'c', 'd', 'e', 'f']

# print the last element
print(my_list[len(my_list)-1])

Output

f
  • We can also use positive indices to access the last element using the above method.
  • We have simply calculated the length of the list, subtracted 1 from it, and accessed that element from the list.
  • The length of the list is 6, subtracting 1 from it will make it 5, so my_list[5] = f.

Check out our other python programming examples

Leave a Reply

Your email address will not be published. Required fields are marked *