Following are the basic tuple operations
1. Adding Element to the Tuple
2. Deleting Tuple
3. Concatenation
4. Repetition
5. in Operator
6. Iteration
1. Adding Element to the Tuple
As we know, that tuples are immutable, hence the data stored in a tuple cannot be edited, but it's definitely possible to add more data to a tuple. This can be done using the addition operator. Suppose there is a tuple,
t=(1, 2, 3, 4)
t = t + ( 5 , )
print(t)
#Output
(1, 2, 3, 4, 5)
Hence, we can add any kind of element to a tuple, using the +
operator.
2. Deleting Tuple
In order to delete a tuple, the del
keyword is used. In order to delete a tuple named myTuple
, follow the example below:
myTuple= (1,2,3,4,5)
print(myTuple)
del(myTuple)
print(myTuple)
#Output
(1, 2, 3, 4, 5)
NameError: name 'myTuple' is not defined
And myTuple
will be deleted from the memory.
3. Concatenation
The concatenation ( + ) operator works in tuple in the same way as it does in lists. This operator concatenation two tuples. This is done by the + operator in Python.
t1=(1, 2, 3, 4)
t2=(5, 6, 7, 8)
t3=t1+t2
print(t3)
#Output
(1, 2, 3, 4, 5, 6, 7, 8)
4. Repetition ( * )
The repetition operator works as its name sugests; it repeats the tuples a given number of ti,es. Repetition is performed by the * operator in Python
tuple=('ok' ,)
tuple=tuple*5
print(tuple)
#Output
('ok', 'ok', 'ok', 'ok', 'ok')
5. in Operator
The in Operator also works on tuples. It tells user that the given element exists in the tuple or not . It gives a Boolean output, i.e. TRUE or FALSE. If the given input is exists in the tuple, it gives the TRUE as a output otherwise FALSE
>>> tuple=(10,20,30,40)
>>> 20 in tuple
True # Output
>>> 50 in tuple
False # Output
6. Iteration
Iteration can be done in the tuples using for loop. It helps in traversing the tuple.
tuple=(10,20,30,40,50)
for i in tuple:
print(i)
#Output
10
20
30
40
50
Lab Assignments:
1. Consider the tuple (1,3,5,7,9,2,4,6,8,10). Write a program to print half its values
in 1 line and the other half in the next line.
t=(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
print(t[:5])
print(t[5:])
#Output
(1, 3, 5, 7, 9)
(2, 4, 6, 8, 10)
2. Consider the tuple (12, 7, 38, 56, 78). Write a program to print another tuple whose values are even number in the given tuple.
t=(12, 7, 38, 56, 78)
even_list=list()
for i in t:
if(i%2==0):
even_list.append(i)
print(even_list)
#Output
[12, 38, 56, 78]
3. Define a function that prints a tuple whose values are the cube of a number between 1 and 10 (Bothe included).
def cube():
l=list()
for i in range(1,11):
l.append(i**3)
print(l)
cube()
#Output
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]