Tuples in Python

Video Tutorial
FREE
Tuples part 1 thumbnail
This video belongs to
Python and SQL for Data Science
8 modules
Certificate

Tuples in python is one of the four inbuilt data types used to store collections in Python. Unlike other data types, the elements in tuples are ordered and immutable. They are used to store multiple items in a single variable and provides some built-in operation to work with them.

Creating a Tuple in Python

Tuples in Python can only be created when they are being assigned, hence placing all the elements inside the parenthesis, separated by a comma will create a tuple. Let’s take a closer look at the syntax:

Output

The parenthesis in the above syntax are optional and hence a tuple can also be created without writing the parenthesis. But remember it’s always a good practice to have the parenthesis, as it always increases the code readability and understanding.

The above snippet can also be written as:

Output

Immutable in Tuples

Tuples in Python are similar to lists but with a key difference: they are immutable. This means once a tuple is created, its elements cannot be changed, added, or removed. Let's break down some characteristics of tuples:

  • Immutable Nature: Once a tuple is created, its elements cannot be modified. This ensures data integrity and stability.
  • Ordered Collection: Like lists, tuples maintain the order of elements as they are inserted.
  • Support for Duplicate Values: Tuples allow duplicate values just like lists.
  • Accessing Elements: Elements in a tuple can be accessed using their index values. Here's an example illustrating the immutability of tuples in python:

When attempting to modify an element within a tuple, Python will raise a TypeError because tuples in python do not support item assignment due to their immutable nature. This constraint ensures that once data is stored in a tuple, it remains unchanged throughout the program's execution.

Python Tuple Types

Python offers two primary types of tuples: named tuples and unnamed tuples.

  • Named tuples: created by subclassing the tuple class and assigning a name to the new class, serve well for representing structured data like records, akin to database entries. Each element within a named tuple corresponds to a field in the record, permitting access by name instead of index. For instance:

Outputs

  • Unnamed Tuples: are more prevalent and are generated simply by separating values with commas. They are suitable for storing unstructured data that doesn't necessitate naming. Here's an example:

Outputs

In this instance, a tuple in python containing three elements is created. Accessing elements within the tuple can be achieved using index notation, akin to how one would interact with a list.

Accessing Elements in a Python Tuple and Indexing

Accessing elements in a tuple is no different then accessing elements in a list. As python follows 0 based indexing hence a tuple with n elements will have indices from 0 through n-1. An index in a tuple is accessed with the index operator [ ]. For example:

Let’s consider a basic tuple:

Nested Python Tuple Accessibility

Accessing Via Negative Indices

Python allows you to access elements of a collection via negative indices. When accessing using a negative index, -1 depicts the last element and -n depicts the first index where n is the length of the index.

Consider the following mapping of positive index with negative index:

accessing tuples via negative indices

Updating Tuples in Python

Adding a new element or deleting one is not really an option when dealing with tuples in python, as they are immutable. Even the elements of the tuple cannot be updated until and unless the element is mutable for example a list.
Let’s take an example

Output

Tuples in python can definitely be reassigned, which is very different from updating a tuple. Reassigning a tuple is redefining the tuple all over again.

Just like strings, we can also concat two or more tuples to form a new tuple using ‘+’ operation or apply repetition on a tuple using ‘*’ operator, just the result here is a python tuple and not a string.

Output

In-built Functions for Tuple

Python has the following inbuilt functions to offer for tuples: slicing in python tuples

  • Concatenation: We will use plus operators(+) to Concatenation of Python Tuples.
  • Nesting: We can do the nesting of tuples means a tuple inside another tuple.```
  • Repetition: We have the ability to form a tuple containing multiple identical elements by duplicating a single element within that tuple.
  • Slicing: Slicing in tuples works the same as it works for a String slicing or any other sequence of elements. Slice is an operator that allows you to fetch a sub collection (in this case a sub tuple) from a collection by slicing it from a start index and a stop index.

    Slice syntax:

tuple[start : stop : step]

  • start: is the starting index of the string, on which slicing operation has to be performed. It determines from where slicing of the string will ‘begin’.
  • stop: is the stopping index of the slicing, ‘until’ which slicing operation has to be performed i.e stop index is excluded while generating the sub-tuple.
  • step: It is an optional argument that defines the steps when iterating the list i.e. it allows us to skip over elements.

Consider the above figure when understanding the following code snippet

Output

  • Deleting: As discussed, python tuples being immutable cannot be updated. Hence once some values are assigned to a tuple, it cannot be deleted. You can delete a tuple as a whole, but deleting a specific value/element in a tuple is not possible.

Output

  • Finding the length: In Python, determining the length of a tuple can be accomplished using the built-in function len(). Simply provide the tuple as an argument to len(). This will return the number of elements contained within the tuple.
  • Multiple Data Types with tuples: Tuples in Python are versatile containers, allowing you to store elements of different data types within the same tuple.
  • Conversion of lists to tuples: In Python, you can transform a list into a tuple effortlessly by utilizing the tuple() constructor and providing the list as its argument.
  • Tuples in a Loop: We can also create a tuple with a single element in it using loops.

Output:

Advantages and Disadvantages of Tuple in Python

Advantages

  • Tuples being immutable, turns out to be a write-protected collection. Tuples can be of advantage when we want to store some secure read only data that we cannot afford to be changed throughout our code.
  • Tuples can store data of multiple data types, that makes them a heterogeneous collection.
  • Tuple being a readonly collection, has a faster iteration. (As they are stored in a single block of memory, and don’t have extra space for storing objects, they have constant set of values)

Disadvantages

  • Tuple’s being write protected, is an advantage but also a disadvantage as it cannot be used when we want to add or delete a specific element. Hence has a limited use case.
  • Syntactically less readable as, tuples can be created by either adding parentheses or by not providing them incase we have more than one element. But not using parentheses in case of one element, will not create a tuple and hence a trailing comma in such case is required. This can makes code readability a bit complex for some.
  • As tuple is a class, it's stored on the heap and is overhead on the garbage collector.

Tuple’s advantages and disadvantages are nothing but its use cases i.e. tuple serves some use cases hence one should know when to use tuple, in order to use it for their advantage. Tuples when used where a list or a dictionary or a set would’ve been used, will turn out to be a disadvantage.

Conclusion

  1. Tuples support integer-based indexing and duplicate elements, enhancing data organization and retrieval.
  2. They can be defined with or without parentheses; however, a trailing comma is necessary without parentheses to signify a tuple.
  3. Optimal use of tuples depends on their intended application; misapplication can lead to inefficiencies, such as substituting for lists, sets, or dictionaries.
  4. Choosing the appropriate data structure requires careful consideration of use cases to ensure efficient data handling and manipulation.