What is a negative index?

Negative index in python :
  • Python list items can be accessed with positive or negative index. 
  • If list of size n then 
0 positive index // first index
1 positive index // second index
(n-1) // last index
-n // first index
-(n-1) // second
-1 // last index
  • List indexes of -x mean the xth item from the end of the list, so n[-1] means the last item in the list n.
  • Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.
  • Ex: 
    • If we have a list a = [1,2,3,4] then a[-1] will refer to 4 and a[-2] refer to 3.

Comments

Popular posts from this blog

What is composite key?

What are the different data types in Python?

What is __repr__ function?