How to Use Tuple in Python

Posted on

Introduction

This is an article where the main content is demonstrating on how to use tuple in Python programming language. Another article which is focusing about how to use another collection data type is already exist. That article exist in this link with the title of ‘Using List in Python’. But on the other hand, this article is focusing to describe about how to use tuple in Python programming language.

How to Use Tuple in Python

In this part, using tuple in Python programming language will be the main part with specific processes. Those processes starts with declaring and defining variable using tuple data type.  After successfully declaring or defining variable with tuple data type, there will a lot more processes exist for manipulating the tuple. Especially, if the tuple already exist with several data inside of it. So, before going on further, start with the declaration or definition for variable using tuple data type.

Declaring and Defining Tuple

In this case, there are two types of declaration or definition for the tuple collection data type. The first one is just a simple declaration or definition without even have to include any data or element. Below is the example for that type of declaration or definition :

tuple_example = ()

Another type of declaration or definition using tuple collection data type is definitely include a certain amount of data in it. So, the declaration or definition of a tuple with several data exist below :

tuple_example = (1,2,3,4,5);

Adding Data in Tuple

After successfully declaring or defining variable which has a tuple collection data type, ther are several aspects which is part of the process for using tuple. One part of the process in this example is adding data in the tuple. So, the following is an example using sequence of script execution in order to demonstrate how to add data in tuple as follows :

 C:\python>python
Python 3.10.5 (tags/v3.10.5:f377153, Jun  6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> tuple_example = (1,2,3,4,5);
>>> print(tuple_example);
(1, 2, 3, 4, 5)
>>> tuple_example += (6,7,8,9,10);
>>> print(tuple_example);
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>>

Removing Data in Tuple

Actually, it is not possible to remove data from a tuple. So, as a way out, it is quite often in order to remove tuple, it will use some additional step. One of the way out is convert the tuple into a list. After removing the data or the element in the list, just return back the modified data from the list to the tuple.

Replacing Data in Tuple

As also removing data in tuple, it is not possible to do it. Since tuple is immutable, after declaring or defining tuple, it is not possible to replace existing data in the tuple.

Leave a Reply