Negative Indexing


The tuple element can also access by using negative indexing. The index of -1 denotes the rightmost element and -2 to the second last item and so on.


thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple[0])
apple


print(thistuple[2])
cherry


print(thistuple[-1])
cherry


print(thistuple[2:5])
('cherry', 'apple', 'cherry')


print(thistuple[:])
('apple', 'banana', 'cherry', 'apple', 'cherry')


Note: we cannot not modify tuple.. we need to convert from tuple to list


l=list(thistuple)
print(l)
['apple', 'banana', 'cherry', 'apple', 'cherry']


l.append("orange")
print(l)
['apple', 'banana', 'cherry', 'apple', 'cherry', 'orange']


l.append(["jackfrutit","sunny"])
print(l)
['apple', 'banana', 'cherry', 'apple', 'cherry', 'orange', ['jackfrutit', 'sunny']]


thistuple=tuple(l)
print(thistuple)
('apple', 'banana', 'cherry', 'apple', 'cherry', 'orange', ['jackfrutit', 'sunny'])


print(type(thistuple))
<class 'tuple'>

==================================================================

Example:

tuple1=(1,2,3,4,5)
print("#example for negative indexing")

print(tuple1[-1])    
print(tuple1[-4])    
print(tuple1[-3:-1])  
print(tuple1[:-1])  
print(tuple1[-2:])


Output:

#example for negative indexing
5
2
(3, 4)
(1, 2, 3, 4)
(4, 5)