Creating Tuple in Python

Creating Tuple in Python

As mentioned before, the tuple is used to store a collection of data. The thing is that the tuples are immutable, which simply means that we cannot alter, insert or remove elements in the tuple. So now, as our very first step towards understanding the tuples, we are going to learn how to create tuples. Basically, we are going to have a look at two different ways to create tuples, using the parentheses (actually the parentheses are optional, but we need to separate the elements with commas), and the elements separated by commas, or we can also use the tuple constructor to create a tuple.

Creating Tuple in Python

Let’s have a look at both ways. Here is a simple program, which demonstrates to us how to create a tuple with the help of parentheses. We would also use the type function, to check the type of object that we would create.

As you can see, we have created a tuple, with some elements into it(you can have it empty as well). After that, we are also checking the type of the tuple. You can try executing the above program and find that the object that we have created is a tuple.

The tuple can have data of different types as well. Let’s have a look at another program, which demonstrates us the same thing.

As you can see, we have a tuple, with different types of data, and after that, we have checked the type of the object. You can try executing the program and observe the output. You can play with the values as well. We can make it more complicated, by having a tuple, or another list inside a tuple, but for now, it can be considered as a big achievement for us, that we have created a tuple.

We can also create a tuple, using the tuple constructor. Let’s have a look at how we can do that. Have a look at the below program, which demonstrates the same thing.

As you can see, we have used the tuple constructor to create a tuple. Here, no argument is passed to the constructor, so an empty tuple is created. If we pass some iterable to the constructor, then the tuple is created from the iterable’s items.

So, these are some of the ways, using which, we can create a tuple. Often, there can be situations, when we need to make use of tuples in our programs. So, we would make use of tuples, as and when required in our python programs.