The items in the tuple can be accessed by using the index [] operator. Python also allows us to use the colon operator to access multiple items in the tuple.
=======================================================================
Example:1
tup = (1,2,3,4,5,6,7)
print(tup[0])
print(tup[1])
print(tup[2])
# It will give the IndexError
print(tup[8])
OUTPUT:
1
2
3
Traceback (most recent call last):
File "C:\Users\mhtpr\Documents\FormatFactory\tuple.py", line 66, in <module>
print(tup[8])
IndexError: tuple index out of range
Note:
the tuple has 7 elements which denote 0 to 6. We tried to access an element outside of tuple that raised an IndexError.
=======================================================================
Example:2
tuple=(1,2,3,4,5,6,7)
print("#element 1 to end")
print(tuple[1:])
print("#element 0 to 3 element")
print(tuple[:4])
print("#element 1 to 4 element")
print(tuple[1:5])
print("# element 1 to 6 and take step of 2")
print(tuple[1:6:2])
print("# element 1 to 6 and take step of 3")
print(tuple[0:6:3])
print("==================================")
Output:
#element 1 to end
(2, 3, 4, 5, 6, 7)
#element 0 to 3 element
(1, 2, 3, 4)
#element 1 to 4 element
(2, 3, 4, 5)
# element 1 to 6 and take step of 2
(2, 4, 6)
# element 1 to 6 and take step of 3
(1, 4)