1.

Python index operator can accept negative numbers. Explain how?

Answer»

Python’s sequence data types (list, tuple or string) are indexed collection of items not necessarily of the same TYPE. INDEX starts from 0 – as in C/C++ or Java array (although these languages insist that an array is a collection of similar data types). Again like C/C++, any element in sequence can be accessed by its index.

>>> num=[10,20,25,15,40,60,23,90,50,80] >>> num[3] 15

However, C/C++/Java don’t allow negative numbers as index. Java throws NegativeArraySizeException. C/C++ produces undefined behaviour. However, Python accepts negative index for sequences and starts counting index from end. Consequently, index -1 returns the last element in the sequence. 

>>> num=[10,20,25,15,40,60,23,90,50,80] >>> num[-1] 80 >>> num[-10] 10

However, using negative index in slice notation exhibits some peculiar behaviour. The slice operator accepts two numbers as operands. First is index of the beginning element of the slice and second is the index of the element after slice. Num[2:5] returns elements with index 2, 3 and 4

>>> num=[10,20,25,15,40,60,23,90,50,80] >>> num[2:5] [25, 15, 40]

Note that default value of first operand is 0 and second is length+1

>>> num=[10,20,25,15,40,60,23,90,50,80] >>> num[:3] [10, 20, 25] >>> num[0:3] [10, 20, 25] >>> num[8:] [50, 80] >>> num[8:10] [50, 80]

Hence using a negative number as the first or second operand gives the results ACCORDINGLY. For example using -3 as the first operand and ignoring the second returns the last THREE items. However, using  -1 as second operand results in leaving out the last element

>>> num[-3:] [90, 50, 80] >>> num[-3:-1] [90, 50]

Using -1 as first operand without second operand is equivalent to indexing with -1

>>> num[-1:] [80] >>> num[-1] 80


Discussion

No Comment Found