Slicing
We can access a range of items in a tuple by using the slicing operator – colon “:”.
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:4]) print(n[:3]) print(n[4:]) print(n[2:5]) print(n[3:7])
Output:
(‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’)
(‘o’, ‘m’, ‘p’)
(‘c’, ‘o’, ‘m’)
(‘u’, ‘t’, ‘e’, ‘r’)
(‘m’, ‘p’, ‘u’)
(‘p’, ‘u’, ‘t’, ‘e’)
n=('c','a','t','a','l','y','s','t') print(n) print(n[1:6]) print(n[3:]) print(n[2:7]) print(n[2:4]) print(n[:4])
Output:
(‘c’, ‘a’, ‘t’, ‘a’, ‘l’, ‘y’, ‘s’, ‘t’)
(‘a’, ‘t’, ‘a’, ‘l’, ‘y’)
(‘a’, ‘l’, ‘y’, ‘s’, ‘t’)
(‘t’, ‘a’, ‘l’, ‘y’, ‘s’)
(‘t’, ‘a’)
(‘c’, ‘a’, ‘t’, ‘a’)
n=(10,20,30,40,50,60,70) print(n) print(n[3:]) print(n[:3]) print(n[2:7]) print(n[:6]) print(n[4:])
Output:
(10, 20, 30, 40, 50, 60, 70)
(40, 50, 60, 70)
(10, 20, 30)
(30, 40, 50, 60, 70)
(10, 20, 30, 40, 50, 60)
(50, 60, 70)
n=('c','o','m','p','u','t','e','r') print(n) print(n[-4:-1]) print(n[:-3]) print(n[-4:]) print(n[-2:-5]) print(n[-3:-7])
Output:
(‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’)
(‘u’, ‘t’, ‘e’)
(‘c’, ‘o’, ‘m’, ‘p’, ‘u’)
(‘u’, ‘t’, ‘e’, ‘r’)
()
()
n=('c','a','t','a','l','y','s','t') print(n) print(n[-6:-1]) print(n[-3:]) print(n[-7:-2]) print(n[-2:-4]) print(n[:-4])
Output:
(‘c’, ‘a’, ‘t’, ‘a’, ‘l’, ‘y’, ‘s’, ‘t’)
(‘t’, ‘a’, ‘l’, ‘y’, ‘s’)
(‘y’, ‘s’, ‘t’)
(‘a’, ‘t’, ‘a’, ‘l’, ‘y’)
()
(‘c’, ‘a’, ‘t’, ‘a’)