Learn everything about tuples

Published On: Sat, 12 Apr 2025 Updated On: Sat, 12 Apr 2025

Python list is a very simple and go-to choice due to its mutability feature and ease of use. But there is one more data structure that Python offers that is equaly useful and incredible. Tuple. Tuple is immutable data sequence with distinct advantages that make it a valuable tool for some use cases. In this chapter, we will dive into tuple data structure, find answers for the below questions:

  1. What is tuple?
  2. How to create tuple in python?
  3. How to access tuple elements?
  4. What are the differences between a list and tuple?
  5. Where can we employ tuples effectively?

So, are you ready for the journey into the Python's Typle Data Structure?

yes, let's get started.

Tuples: The Immutable Sequences

Python tuple is a data structure that stores the collection of elements of various data types in order. The primary distinction between tuple and list reside in their mutability. While we can modify list after it has been created, tuple is immutable, meaning the elements cannot be changed, added, or removed once the tuple is created. This means the value is constant and can not be changed during the lifetime of a program. This immutability makes tuples ideal for scenarios where data integrity and safety are crucial. For example, data retrived from a database table.

Did you ever notice what it returns is a list of tuples?

Let me know in comments if you knew this or you checked it after reading this.

My next question to you is why it uses list of tuples for database table records? Why not list of lists or tuple of lists or tuple of tuples?

Think about it. 😇

Meanwhile, let's look at how we can create and access tuple elements.

Creating and Accessing Tuples

Creating tuples is straightforward; we can define a tuple by enclosing its elements in parentheses () and separating elements with comma. Let us look at a simple example:

Code Example
# Simplest way of creating tuple of strings
fruits = ('apple', 'orange', 'banana', 'grape')

We can access the tuple elements same as we access a list element. We can use indexing and slicing to retrieve specific elements or a subset of elements from the tuple. For instance:

Code Example
# Accessing elements in a tuple
print(fruits[0])     # Output: 'apple'
print(fruits[1:3])   # Output: ('orange', 'banana')

Tuple Packing and Unpacking

Tuple packing and unpacking are potent features in Python. Packing involves assigning multiple values to a single tuple, whereas unpacking allows us to extract values from a tuple into individual variables. Consider this example:

Code Example
# Tuple packing
point = (10, 20)

# Tuple unpacking
x, y = point
print(f"x: {x}, y: {y}")   # Output: x: 10, y: 20

Difference Between List and Tuple

While both list and tuple store collections of items, their unique characteristics make them suitable for different scenarios. Here are some key differences and best use cases for each:

  • Lists
    • Lists are mutable, allowing for easy modification of elements.
    • They use more memory than tuples due to the overhead of additional functionalities.
    • Ideal for situations where data needs to be frequently modified, such as a to-do list.
  • Tuples
    • Tuples are immutable, ensuring data integrity and safety.
    • They are slightly more memory-efficient than lists.
    • Well-suited for representing fixed data, such as coordinates, RGB values of colors, or database records.

Best Use Cases

Consider the following example to demonstrate the best use cases for tuples:

Code Example
# Using a list for a to-do list
to_do_list = ["Task 1", "Task 2", "Task 3"]
to_do_list[1] = "Task 2 (Completed)"

# Using a tuple for coordinates
coordinates = (10, 20)
# coordinates[0] = 5   # This will raise an error as tuples are immutable

Tuple Internals

Tuples in Python are implemented as a contiguous array of pointers to Python objects. Here's a breakdown of the internal structure:

Tuple Object Structure

A tuple object in Python is represented by the PyTupleObject struct, which contains the following members:
ob_refcnt: reference count
ob_type: type object
ob_size: size of the tuple
ob_item: array of pointers to Python objects
 
Code Example
typedef struct {
    PyObject_VAR_HEAD
    PyObject *ob_item[1];
} PyTupleObject;

When you create a tuple, Python allocates memory for the tuple object and initializes the ob_item array with pointers to the objects you're storing in the tuple.

Consider the following tuple:

Code Example
my_tuple = (1, 2, 3)

Internally, Python creates a tuple object with ob_size set to 3 and ob_item pointing to an array of three pointers:

item[0]: pointer to the integer object 1
item[1]: pointer to the integer object 2
item[2]: pointer to the integer object 3

Benefits

This implementation provides several benefits:
Efficient memory usage: Tuples store pointers to objects, which reduces memory overhead.
Fast indexing: Tuples support fast indexing due to their contiguous memory layout.
Immutability: Tuples are immutable, which ensures that their contents cannot be modified accidentally.

Interview Question

Why Tuple is faster than list?

Looking forward to your answers in comment section.

Conclusion

Tuples are valuable to Python's data structures, providing immutability and efficient data handling capabilities. While lists remain popular for general-purpose data storage and manipulation, tuples shine in scenarios where data integrity, safety, and memory efficiency are paramount. By understanding the strengths and best use cases of tuples, Python developers can make informed decisions on when to employ tuples to their advantage, streamlining their code and enhancing overall performance.

So, when dealing with fixed data or ensuring data immutability, consider the power and simplicity of tuples in Python. Happy coding!

Learn everything about tuples

Reader Comments


Add a Comment