tuple is immutable [No Modification or Update] data type.list except that a tuple is immutable.list can be applied to tuple, except the ones that modify the content of tuple.tuple is specified using parentheses () instead of square brackets [].tuple¶tuple_name = (item1, item2, ..., itemn)
Alternatively
tuple_name = item1, item2, ..., itemn
# Create a tuple which stores the student's information like Reg.no, Rank
student_info = ('21MIA000', 1)
print(f'student_info is {student_info}' )
student_info is ('21MIA000', 1)
# Individual items in a tuple can be accessed using index
# indexing is similar to list starts with 0
print(f'student Reg.No is {student_info[0]}, and Rank is {student_info[1]}' )
student Reg.No is 21MIA000, and Rank is 1
# A single element tuple can be defined by placing an element followed by "," in ()
tuple_1 = (10,)
print("tuple_1 ", tuple_1)
tuple_1 (10,)
# we will now find the length of the tuple with len built in function
print(len(tuple_1))
1
# let's now try to modify the value of an element in the tuple
# Remember that TUPLE IS IMMUTABLE ... IT IS IMMUTABLE!
tuple_1[0] = 2
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [5], in <cell line: 3>() 1 # let's now try to modify the value of an element in the tuple 2 # Remember that TUPLE IS IMMUTABLE ... IT IS IMMUTABLE! ----> 3 tuple_1[0] = 2 TypeError: 'tuple' object does not support item assignment
tuple¶t1 = (1,2)
t2 = (5,6)
t = t1 + t2
# Try Guessing the answer
print("t1 + t2 = ", t)
t1 + t2 = (1, 2, 5, 6)
t1 = (1,2)
t = t1 * 5
# Try Guessing the answer
print("t1 * 5 = ", t)
t1 * 5 = (1, 2, 1, 2, 1, 2, 1, 2, 1, 2)
# Slicing works in tuples in the way as that of lists
print("t[1:3] is ", t[1:3])
t[1:3] is (2, 1)
# count to find the number of occurences
print('count number of 1s in t ', t.count(1))
count number of 1s in t 5
# index methods to find the position
print(t.index(2))
1
help(tuple)
Help on class tuple in module builtins: class tuple(object) | tuple(iterable=(), /) | | Built-in immutable sequence. | | If no argument is given, the constructor returns an empty tuple. | If iterable is specified the tuple is initialized from iterable's items. | | If the argument is a tuple, the return value is the same object. | | Built-in subclasses: | asyncgen_hooks | UnraisableHookArgs | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return key in self. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(self, key, /) | Return self[key]. | | __getnewargs__(self, /) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __repr__(self, /) | Return repr(self). | | __rmul__(self, value, /) | Return value*self. | | count(self, value, /) | Return number of occurrences of value. | | index(self, value, start=0, stop=9223372036854775807, /) | Return first index of value. | | Raises ValueError if the value is not present. | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) from builtins.type | See PEP 585 | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature.
# Create a tuple with a mutable objct as an item in it
tup = (1, [2, 3], 4)
print(tup[1][1])
3
# Let's now change the element inside the list
tup[1] = [7,8]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [15], in <cell line: 2>() 1 # Let's now change the element inside the list ----> 2 tup[1] = [7,8] TypeError: 'tuple' object does not support item assignment
# Let's now change the mutable element inside the list
tup[1][0] = 5
print(tup)
(1, [5, 3], 4)
tuple - membership operator¶# we will now see how to use 'in' operator to check the membership
if (4 in (tup)):
print(" 4 is present in tup")
else:
print(" 4 is not present in tup")
4 is present in tup
# Check if 5 is present in tup
if (5 in (tup)):
print(" 5 is present in tup")
else:
print(" 5 is not present in tup")
5 is not present in tup
# Check if 5 is present in tup[1]
if (5 in (tup[1])):
print(" 5 is present in tup[1]")
else:
print(" 5 is not present in tup[1]")
5 is present in tup[1]
#find the max and min elements in a tuple
tup = (3, 6, 1, 9, 4)
print(f'{max(tup)} is the max element and {min(tup)} is the min element in tup')
9 is the max element and 1 is the min element in tup
my_list = [2, 5, 3, 'aaa']
t = tuple(my_list)
print(t)
(2, 5, 3, 'aaa')
# Create a dictionary
dict1 = dict(name ='John', age= 32, job_roles= ['dev', 'mgr'])
dict2 = dict([('name' ,'John'), ('age', 32), ('job_roles', ['dev', 'mgr'])])
print(dict1)
print(dict2)
{'name': 'John', 'age': 32, 'job_roles': ['dev', 'mgr']}
{'name': 'John', 'age': 32, 'job_roles': ['dev', 'mgr']}
# Creating a tuple
dict1['name'], dict1['age']
('John', 32)
# create a tuple with the values of a dictionary
t = tuple(dict1.values())
print(t)
('John', 32, ['dev', 'mgr'])