Why Python Returns Tuple in List Instead of List in List



In Python, especially in situations like iterating through data structures, working with built-in functions, or fetching records from a database, lists of tuples are returned by the pre-defined functions instead of a list of lists.

This is because tuples are immutable i.e., we cannot modify them after creation, whereas lists are mutable; once obtained, we can change their contents. This makes tuples ideal for storing fixed data like database records or function results, ensuring data integrity. Let us see methods/functions in Python that return a list of tuples -

The enumerate() Function

The enumerate() function is used to add a counter to an iterable(like a list). When you convert the result of enumerate() into a list, it gives you a list of tuples. Each tuple contains the index and the value from the original iterable.

Example

In the following example, each item in the result is a tuple containing the index and the fruit. Because tuples are immutable, each pair remains fixed.

fruits = ['apple', 'banana', 'cherry']
result = list(enumerate(fruits))
print(result)

Following is the output of the above code -

[(0, 'apple'), (1, 'banana'), (2, 'cherry')]

The zip() Function

The zip() function will combine multiple iterables (like lists) into a single iterable, where elements are paired together. It returns a zip object, which is typically converted into a list of tuples. Each tuple here represents grouped data from the original iterables.

Example

In this example, each tuple holds a name and an age. These pairs act like records that should not be changed, so tuples are the right choice.

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 22]

combined = list(zip(names, ages))
print(combined)

Following is the output of the above code -

[('Praveen', 25), ('Suresh', 30), ('Charlie', 22)]

While Retrieving Query Results (Rows as Tuples)

In many database libraries like SQLite in Python, when we run a query, the results are often a list of tuples. Each tuple represents a full row and offers data protection. Since each row structure (column values) should not be accidentally changed.

Example

Here, each tuple contains employee details. Returning them as tuples helps each record stay uneditable. Here, each tuple contains employee details. Returning them as tuples helps ensure each record stays uneditable unless intentionally changed.

# Simulating a database result
rows = [
    (1, 'Rahul', 'HR'),
    (2, 'Rita', 'Finance'),
    (3, 'Praveen', 'IT')
]
for row in rows:
    print(row)

Following is the output of the above code -

(1, 'Rahul', 'HR')
(2, 'Rita', 'Finance')
(3, 'Praveen', 'IT')
Updated on: 2025-04-15T12:23:49+05:30

364 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements