Tuples
Tuples
Tuple – A tuple contains a group of elements which can be same or different types.
Tuples are immutable.
It is similar to List but Tuples are read-only which means we can not modify it’s
element.
Tuples are used to store data which should not be modified.
It occupies less memory compare to list.
Tuples are represented using parentheses ( ).
Ex:- a = (10, 20, -50, 21.3, ‘Geekyshows’)
Creating Empty Tuple
Syntax:- tuple_name = ( )
Ex:- a = ( )
Creating Tuple
We can create tuple by writing elements separated by commas inside parentheses.
[0] 10 [-5] 10
[1] 20 [-4] 20
a [2] -50 a [-3] -50
[3] 21.3 [-2] 21.3
[4] Geekyshows [-1] Geekyshows
Accessing Tuple’s Element
a = (10, 20, -50, 21.3, ‘Geekyshows’)
print(a[0])
print(a[1]) 10 20 -50 21.3 Geekyshows
a[0] a[1] a[2] a[3] a[4]
print(a[2])
print(a[3])
print(a[4])
Accessing using for loop
a = (10, 20, -50, 21.3, ‘Geekyshows’)
Without index
for element in a:
print(element)
With index
n = len(a)
for i in range(n):
print(a[i])
Accessing using while loop
a = (10, 20, -50, 21.3, ‘Geekyshows’)
n = len(a)
i=0
while i < n :
print(a[i])
i+=1
Slicing on Tuple
Slicing on tuple can be used to retrieve a piece of the tuple that contains a
group of elements. Slicing is useful to retrieve a range of elements.
Syntax:-
new_tuple_name = tuple_name[start:stop:stepsize]
Tuple Concatenation
+ operator is used to do concatenation the tuple.
Ex:-
a = (10, 20, 30)
b = (1, 2, 3)
result = a + b
print(result)
Modifying Element
Tuples are immutable so it is not possible to modify, update or delete it’s
element.
a = (10, 20, -50, 21.3, ‘Geekyshows’)
10 20 -50 21.3 Geekyshows
a[1] = 40
a[0] a[1] a[2] a[3] a[4]
b = (101, 102, 103)
10 20 30 40 50
Copying Tuple
We can copy elements of tuple into another tuple using slice.
a = (10, 20, 30, 40, 50)
a
b=a
b = a[0:5]
10 20 30 40 50
b = a[1:4]
[0] [1] [2] [3] [4]