Tuple Constructor in Python Language

In this article, we will study Tuple Constructor using Python Language. For this task, we need to understand the concept of Constructor because it is essential.

A constructor is a special type of method. It intializes the instance members of the class. They are automatically invoked upon creation of a new object.

Let’s understand this concept using an example. A task is given to Shruti. She has to distribute 5 pens to her friends. A fixed pattern is given to her. Machine is required to manufacture pens which will take sequence of actions to produce pen of similar pattern.

Once machine gets pattern it can produce any number of items. In this case, pattern is class, machine is constructor and the number of pens produced is object.

constructor in python

Hence, an object cannot be created if we don’t have a constructor in our program.

Tuple Constructor

Let us now look tuple constructor using Python Language. A tuple is a sequence. Tuple is used to store immutable objects. Immutable means whose value cannot be changed. Items in tuple are stored in order. Hence, tuple is a collection of ordered and immutable objects.

Tuples in Python is declared as:

t = (1,2,3,4,5)

I) tuple(iterable)

In Python, tuple(iterable) is tuple constructor. It is used to create tuple. It can also be used to convert a sequence like lists and dictionaries into tuple.

i) type(sequence)

In Python, type(seq) returns the type of sequence. Sequence can be lists, dictionaries, tuple, string, etc.

t = ("Codespeedy",2,800,7.9)
type(t)

The output will be:

<class 'tuple'>

ii) tuple(list)

In Python, tuple(list) takes list as sequence. List is collection of ordered and mutable items. It will convert list into tuple.

l = [1,2,3,"Codespeedy"]
tuple(l)

Output is:

(1, 2, 3, 'Codespeedy')

iii) tuple(string)

In Python, tuple(string) takes string as sequence. It will convert string into tuple by breaking each character of string as element of tuple.

s = "Rani"
tuple(s)

OUTPUT:

('R', 'a', 'n', 'i')

iv) tuple(dictionary)

In Python, tuple(dict) takes dictionary as sequence. A dictionary is a collection of unordered, changeable and indexed items. It will convert dictionary into tuple. Tuple will contain Keys of dictionaries.

d = {1:"One",2:"Two",3:"Three",4:"Four",5:"Five"}
tuple(d)

OUTPUT:

(1, 2, 3, 4, 5)

v) tuple()

In Python, tuple() takes no parameter. Hence, it will create an empty tuple.

t = tuple()
print("Empty tuple:",t)

OUTPUT:

Empty tuple: ()

Thank You.

You may also read: Invoke the super constructor with Python

Leave a Reply

Your email address will not be published. Required fields are marked *