Accessing Elements in a Tuple
There are various ways in which we can access the elements of a tuple.
Indexing
- We can use the index operator [] to access an item in a tuple where the index starts from 0.
- So, a tuple having 6 elements will have index from 0 to 5. Trying to access an element other that (6, 7,…) will raise an IndexError.
- The index must be an integer, so we cannot use float or other types. This will result into TypeError.
- Likewise, nested tuple are accessed using nested indexing, as shown in the example below.
c=(‘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 |
Example:
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:
Output:
(‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’)
o
p
u
t
r
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’)
o
p
u
t
r
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’)
a
a
t
s
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)
20
40
30
70
50