Friday 18 December 2020

Python: access last element of a list

In python, specifying the index number as -1, you can access the last element of the list. It is useful, if you want to access the last element without calculating the length of the list.

>>> primes = [2, 3, 5, 7, 11, 13]
>>> 
>>> primes[-1]
13

 

Similarly, -2 access the 2nd elements from the end of list, -3 access the 3rd element from the end of list and so on.

>>> primes[-2]
11
>>> 
>>> primes[-3]
7

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment