Professional Documents
Culture Documents
1. DEFINING TUPLE
my_tuple = () # empty tuple-Output: ()
print(my_tuple)
my_tuple = (1, 2, 3) # tuple having integers-Output: (1, 2, 3)
print(my_tuple)
my_tuple = (1, "Hello", 3.4) # tuple with mixed datatypes-Output: (1,
"Hello", 3.4
print(my_tuple)
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) # nested tuple- Output:
("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
# tuple can be created without parentheses - also called tuple packing
my_tuple = 3, 4.6, "dog"
print(my_tuple) # Output: 3, 4.6, "dog"
# tuple unpacking is also possible
a, b, c = my_tuple
print(a) #3
print(b) # 4.6
print(c) # dog
Output:
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
(3, 4.6, 'dog')
3
4.6
dog
# parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # Output: <class 'tuple'>
Output:
<class 'str'>
<class 'tuple'>
<class 'tuple'>
Output:
t
p
('r', 'o', 'g')
('p', 'r')
('i', 'z')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
5. CHANG IN VALUES
my_tuple = (4, 2, 3, [6, 5])
# we cannot change an element in tuple
# TypeError: 'tuple' object does not support item assignment
#my_tuple[1] = 9
Output:
(4, 2, 3, [9, 5])
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
my_tuple = ('p','r','o','g','r','a','m','i','z')
print(my_tuple)
# can't delete items
# TypeError: 'tuple' object doesn't support item deletion
#del my_tuple[3]
Output:
(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Output:
2
4
True
False
True
Output:
Hello John
Hello Kate
Hello Mick
Hello harry
Output:
('Rohan', 'Physics', 21, 69.75)
(1, 2, 3, 4, 5)
('a', 'b', 'c', 'd', 'a', 'd', 'g')
(25.5, True, -55, (1+2j))
('mouse', [8, 4, 6], (1, 2, 3))
c
d
('b', 'c', 'd')
('a', 'b', 'c', 'd')
('c', 'd', 'a', 'd', 'g')
2
1
2
True
False
False
True