Tuple
A Tuple is a collection of Python objects separated by commas.
In someways a tuple is similar to a list in terms of indexing, nested objects and repetition but a tuple is immutable unlike lists which are mutable.
Example - 1:
# Creating non-empty tuples
# One way of creation
tup = 'python', 'gyansetu'
print(tup)
# Another for doing the same
tup = ('python', 'gyansetu')
print(tup)
('python', 'gyansetu')
('python', 'gyansetu')
Example - 2:
t = ( 5,6,7)
print(t)
print(type(t))
(5, 6, 7)
<class 'tuple'>
Example - 3:
#code to test that tuples are immutable
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
TypeError Traceback (most recent call last)
in () 2 3 tuple1 = (0, 1, 2, 3) ----> 4 tuple1[0] = 4 5 print(tuple1)
TypeError: 'tuple' object does not support item assignment
Example - 4:
l1 = [ 1,2,3]
l2 = [4,5,6]
t1 = ('hi','hello')
t2 = ('bye',1,2,3)
t3 = t1 + t2 #add both the tuples
print(t1)
print(t2)
print(t3)
l3 = l1+l2
print(l1)
print(l2)
print(l3)
('hi', 'hello')
('bye', 1, 2, 3)
('hi', 'hello', 'bye', 1, 2, 3)
[1, 2, 3]
[4, 5, 6]
[1, 2, 3, 4, 5, 6]
Example - 5:
# code to test slicing
tuple1 = (0 ,1, 2, 3)
print(tuple1[1:])
print(tuple1[::-1])
print(tuple1[2:4])
(1, 2, 3)
(3, 2, 1, 0)
(2, 3)
Example - 6:
# Code for printing the length of a tuple
tuple2 = ('python', 'awesome')
print(len(tuple2))
2
Example - 7:
# Code for converting a list and a string into a tuple
list1 = [0, 1, 2]
print(tuple(list1))
print(tuple(('python'))) # string 'python'
(0, 1, 2)
('p', 'y', 't', 'h', 'o', 'n')
Last updated
Was this helpful?