Programming for Data Science¶

tuple¶

Dr. Bhargavi R

SCOPE, VIT Chennai

  • tuple is yet another sequence data type.
  • tuple is immutable [No Modification or Update] data type.
  • Same as list except that a tuple is immutable.
  • All the operations that can be applied on list can be applied to tuple, except the ones that modify the content of tuple.
  • A tuple is specified using parentheses () instead of square brackets [].
  • Can be used as a key to dictionary since this is immutable.

Creating a tuple¶

tuple_name = (item1, item2, ..., itemn)
Alternatively
tuple_name = item1, item2, ..., itemn
In [1]:
# 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)
In [2]:
# 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
In [3]:
# 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,)
In [4]:
# we will now find the length of the tuple with len built in function
print(len(tuple_1))
1
In [5]:
# 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

Operations on tuple¶

In [6]:
t1 = (1,2)
t2 = (5,6)
t  = t1 + t2
# Try Guessing the answer
In [7]:
print("t1 + t2 = ", t)
t1 + t2 =  (1, 2, 5, 6)
In [8]:
t1 = (1,2)
t  = t1 * 5
# Try Guessing the answer
In [9]:
print("t1 * 5 = ", t)
t1 * 5 =  (1, 2, 1, 2, 1, 2, 1, 2, 1, 2)

Slicing and other operatoins on a tuple¶

In [10]:
# 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)
In [11]:
# count to find the number of occurences
print('count number of 1s in t ', t.count(1))
count number of 1s in t  5
In [12]:
# index methods to find the position
print(t.index(2))
1
In [13]:
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.

In [14]:
# Create a tuple with a mutable objct as an item in it
tup = (1, [2, 3], 4) 
print(tup[1][1])
3
In [15]:
# 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

That's because tuple is immutable¶

In [16]:
# Let's now change the mutable element inside the list
tup[1][0] = 5
In [17]:
print(tup)
(1, [5, 3], 4)

tuple - membership operator¶

In [18]:
# 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
In [19]:
# 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
In [20]:
# 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]

More Methods...¶

In [21]:
#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

Create a tuple from a list¶

In [22]:
my_list = [2, 5, 3, 'aaa']
t       = tuple(my_list)
In [23]:
print(t)
(2, 5, 3, 'aaa')

Creating a Dictionary record from tuple¶

In [24]:
# 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']}
In [25]:
# Creating a tuple
dict1['name'], dict1['age']
Out[25]:
('John', 32)
In [26]:
# create a tuple with the values of a dictionary
t = tuple(dict1.values())
print(t)
('John', 32, ['dev', 'mgr'])