CBSE Class 11 : Python | Tuples 4

Negative Indexing

Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on.

 

n=(‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’)

Positive index

0

1

2

3

4

5

6

7

c

o

m

p

u

t

e

r

-8

-7

-6

-5

-4

-3

-2

-1

Negative index

n=('c','o','m','p','u','t','e','r')
print(n)
print(n[-1])
print(n[-3])
print(n[-4])
print(n[-5])
print(n[-7])

Output:

(‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’)
r
t
u
p
o

 

n=('c','a','t','a','l','y','s','t')
print(n)
print(n[-1])
print(n[-3])
print(n[-2])
print(n[-6])
print(n[-4])

Output:

(‘c’, ‘a’, ‘t’, ‘a’, ‘l’, ‘y’, ‘s’, ‘t’)
t
y
s
t
l

n=(10,20,30,40,50,60,70)
print(n)
print(n[-1])
print(n[-3])
print(n[-2])
print(n[-6])
print(n[-4])

Output:

(10, 20, 30, 40, 50, 60, 70)
70
50
60
20
40