Write a program to demonstrate tuple in python
What is tuple in Python with example?
Tuple is a sequence of python objects like list with immutable feature. We cannot add or remove an item in tuple. Tuples are created by ( ). It contains heterogeneous data-types.
eg: t=(1,2,'hello',20.5)
# An empty tuple
t = ()
print (t)
tup = 'python', 'tuple'
print(tup)
Output
()
('python', 'tuple')
# Another for doing the same
tup = ('python', 'GoEduHub')
print(tup)
Output
('python', 'GoEduHub')
Functions in Tuple
len(tuple) |
Gives the total length of the tuple.
|
max(tuple) |
Returns item from the tuple with max value. |
min(tuple) |
Returns item from the tuple with min value.
|
tuple(seq) |
Converts a list into tuple.
|
# concatenating 2 tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'GoEduhub')
print(tuple1 + tuple2)
Output
(0, 1, 2, 3, 'python', 'GoEduhub')
#nested tupples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'GoEduHub')
tuple3 = (tuple1, tuple2)
print(tuple3)
Output
((0, 1, 2, 3), ('python', 'GoEduHub'))
#tuple repitition
tuple3 = ('python',)*3
print(tuple3)
Output
('python', 'python', 'python')
#tuples are immutable
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
Output
#slicing
tuple1 = (0 ,1, 2, 3)
print(tuple1[1:])
print(tuple1[::-1])
print(tuple1[2:4])
Output
(1, 2, 3)
(3, 2, 1, 0)
(2, 3)
#deleting a tuple
tuple3 = ( 0, 1)
del tuple3
print(tuple3)
Output
#length of a tuple
tuple2 = ('python', 'goeduhub')
print(len(tuple2))
Output
2
#converting a list and a string into a tuple
list1 = [0, 1, 2]
print(tuple(list1))
print(tuple('python')) # string 'python'
Output
(0, 1, 2)
('p', 'y', 't', 'h', 'o', 'n')
#tuples in a loop
tup = ('h','e','l','l','o')
for i in tup:
print(i)
Output
h
e
l
l
o
For more Rajasthan Technical University CSE VI Sem Python Lab Experiments Click here