We can access elements in tuple by referring to index number just like list.
Syntax:
item = tuple[index]
Example:
tup = (1,2,3,4,5,6)
1 | 2 | 3 | 4 | 5 | 6 |
Access Tuple Item:
- tup[0] = 1
- tup[0:] = (1, 2, 3, 4, 5, 6)
- tup[1] = 2
- tup[2:] = (3, 4, 5, 6)
- tup[3:5] = (4, 5)
- tup[2:6] = (3, 4, 5, 6)
Access Tuple using Negative Index:
-1
refers to the last item and so on.
- tup[-2] = 5
- tup[-4:-1] = (3,4,5)
- tup[-3] = 4
- tup[-5:-1] = (2,3,4,5)
- tup[-4] = 3
Access Tuple using if Item exist:
It is used to check if a specified item is present in a tuple use the in
keyword.
tup = (1,2,3,4,5,6)
if 2 in tup:
print("Yes!!!")
Output: Yes!!!
- Log in to post comments