Blog

Tuples in Python

Tuples are used to store multiple items in a single variable. Tuples are the collection of items. It is immutable. Tuples are written with round brackets.

Accessing the elements of tuple

Tuples are immutable

You cannot change the elements in tuple.

Finding number of items in a tuple

We can use len() function to find out the number of items in a tuple just like lists.

Deleting a tuple

Creating Empty Tuple

The empty tuple is written as two parentheses containing nothing

tup1 = ();

Tuple containing one value

To write a tuple containing a single value you have to include a comma, even though there is only one value − tup1 = (50,);

Basic Tuples Operations

Some operations like length, concatenation, repetition and membership are shown below.

List Vs Tuple

Lists and Tuples are used to store one or more Python objects or data-types sequentially. Both can store any data such as integer, float, string, and dictionary. Lists and Tuples are similar in most factors but there are some significant differences between them.

Representation Differences : List are commonly enclosed with the square bracket [] and Tuples are enclosed with parenthesis ().

Mutable Lists and Immutable Tuples: It is the most important difference between list and tuple whereas lists are mutable, and tuples are immutable. The lists are mutable which means the Python object can be modified after creation, whereas tuples can’t be modified after creation.

Debugging: The tuples are easy to debug in a big project because of its immutability. If we have a small project or less number of data, then lists play an effective role.

In the above code, we did b = a; here we are not copying the list object from b to a. The b referred to the address of the list a.  It means if we make the change in the b then that will reflect the same as in list a, and it makes debugging easy. But it is hard for the significant project where Python objects may have multiple references. It will be very complicated to track those changes in lists but immutable object tuple can’t change after created. So tuples are easy to debug.

Functions Support: The tuples support less operation than the list. The inbuilt dir(object) is used to get all the supported functions for the list and tuple.

Memory Efficient: The tuples are more memory efficient than the list because tuple has less built-in operations. Lists are suitable for the fewer elements whereas tuples are a bit faster than the list for the huge amount of data.

One thought on “Tuples in Python

Leave a Reply

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