Concepts / Working with Lists and Tuples

Working with Lists and Tuples

There are four built-in data structures in Python list, tuple, dictionary and set . We will see how to use each of them and how they make life easier for us.

  • Programming

What Lists and Tuples Are

Python provides four built-in data structures to organize and store multiple values: lists, tuples, dictionaries, and sets. In this article, we focus on the first two: lists and tuples. Both allow you to hold multiple objects together in a single container. Think of them as collections that group related data. The key difference is what you can do with them after you create them. A list is like a flexible notebook where you can add, remove, or change entries whenever you want. A tuple is like a sealed envelope—once you seal it, you cannot change what is inside.

A list is a mutable, ordered collection of objects in Python. You create a list using square brackets and separate items with commas. A tuple is an immutable, ordered collection of objects. You create a tuple using parentheses and separate items with commas. The immutability of tuples means you cannot modify, add, or remove elements after the tuple is created.

Accessing Elements by Position

Both lists and tuples are ordered, meaning each element has a specific position. You access items in a list or tuple by specifying the item's position within square brackets. This is called the indexing operator. Python uses zero-based indexing, so the first item is at position 0, the second at position 1, and so on. You can also access nested elements—if a list or tuple contains another list or tuple, you can use multiple index operators in sequence to drill down into the nested structure.

python
Output (expected)
apple
20
tiger
elephant

A list within a list does not lose its identity—lists are not flattened. The same applies to a tuple within a tuple, or a tuple within a list, or a list within a tuple. Python treats them as objects stored within another object, preserving their structure.

The Mutability Difference

The most important distinction between lists and tuples is mutability. A list is mutable, meaning you can change its contents after creation. You can modify an element, add new elements, or remove elements. A tuple is immutable, meaning once it is created, you cannot change, add, or remove any elements. This immutability is a core feature of tuples, similar to how strings cannot be modified in Python.

my_list[1] = 99my_tuple[1] = 99my_list[10, 20, 30]my_list[10, 99, 30]my_tuple(10, 20, 30)my_tupleTypeError: 'tuple' objectdoes not support itemassignment
What happens when you try to change an element at index 1? Lists allow the change; tuples raise an error.
python
Output (expected)
[10, 99, 30]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

How Lists and Tuples Are Stored in Memory

Both lists and tuples store their elements in a contiguous block of memory, with each element accessible by its index position. When you create a list or tuple, Python allocates memory to hold references to the objects in that collection. Each position in the collection corresponds to a specific memory location. This ordered storage is what makes indexing fast and predictable. The key difference is that a list's memory block can be resized when you add or remove elements, while a tuple's memory block is fixed at creation time.

Index 0'apple'Index 010Index 1'banana'Index 120Index 2'cherry'Index 230
How are elements stored in memory? Each index position maps to a specific location holding a reference to the object.

Working with Nested Structures

Lists and tuples can contain other lists and tuples. When you nest one collection inside another, the inner collection is stored as a single element in the outer collection. This allows you to create complex, hierarchical data structures. You access nested elements by chaining index operators: the first index selects which element in the outer collection, and the second index selects which element within that inner collection.

zoo[0]zoo[1]zoo[0][0]zoo[0][1]zoo[1][0]zoo[1][1]zooElement 0['lion', 'tiger']Index 0'lion'Element 1('elephant', 'giraffe')Index 1'tiger'Index 0'elephant'Index 1'giraffe'
How are nested structures organized? Each inner collection is a single element in the outer collection.

Accessing Elements in a Nested Structure

You have a nested structure representing a zoo: zoo = [['lion', 'tiger'], ('elephant', 'giraffe')]. What is the value at zoo[1][0]? What about zoo[0][1]?

Identify the outer index: zoo[1] refers to the second element of the outer list, which is the tuple ('elephant', 'giraffe').

Apply the inner index: zoo[1][0] refers to the first element of that tuple, which is 'elephant'.

Repeat for the second query: zoo[0] refers to the first element of the outer list, which is the list ['lion', 'tiger']. zoo[0][1] refers to the second element of that list, which is 'tiger'.

zoo[1][0] = 'elephant' and zoo[0][1] = 'tiger'

python
Output (expected)
['lion', 'tiger']
('elephant', 'giraffe')
lion
giraffe
['leopard', 'tiger']

Common Mistakes with Lists and Tuples

  • Attempting to modify a tuple after creation

    Tuples are immutable. Once created, you cannot change any element. This raises a TypeError.

    Fix: If you need to modify the data, use a list instead: my_list = [1, 2, 3]; my_list[0] = 10

  • Forgetting that lists are mutable and shared references can cause unexpected changes

    list2 = list1 does not create a copy; it creates another reference to the same list. Modifying list2 also modifies list1.

    Fix: To create a copy, use list2 = list1.copy() or list2 = list1[:]. Now modifications to list2 do not affect list1.

  • Confusing the syntax for creating a single-element tuple

    This creates an integer 5, not a tuple. The parentheses are just grouping, not tuple syntax.

    Fix: To create a single-element tuple, use a trailing comma: single = (5,)

  • Assuming nested structures are flattened

    Nested lists are not flattened. The outer list has 2 elements, each of which is itself a list.

    Fix: Understand that nested structures preserve their hierarchy. To access individual elements, use multiple indices: nested[0][0] gives 1.

When to Use Lists vs. Tuples

AspectListTuple
MutabilityMutable—can be modified after creationImmutable—cannot be modified after creation
SyntaxSquare brackets: [1, 2, 3]Parentheses: (1, 2, 3)
PerformanceSlightly slower due to mutability overheadSlightly faster due to immutability
Use CaseWhen data needs to change (add, remove, modify elements)When data should remain constant (e.g., dictionary keys, function return values)
HashableNo—cannot be used as dictionary keysYes—can be used as dictionary keys if all elements are hashable
Common Operationsappend(), insert(), remove(), pop(), extend()Indexing, slicing, iteration (no modification methods)

Use a list when you need a collection that can grow, shrink, or change. Use a tuple when you need a collection that should remain constant and you want to signal to other programmers (and to Python) that the data is not meant to be modified. Tuples are also useful as dictionary keys because they are hashable, whereas lists are not.

python
Output (expected)
['milk', 'eggs', 'butter']
origin
Alice

Practice: Identifying and Working with Lists and Tuples

MEDIUM

You are given the following data structure: data = [('Alice', 25), ('Bob', 30), ('Charlie', 28)]. This is a list of tuples, where each tuple contains a name and an age. Write code to access the name of the second person (Bob) and the age of the third person (Charlie). Then, explain why you cannot modify the tuples directly but could modify the list itself.

Hints
  • Remember that lists use zero-based indexing, so the second person is at index 1.
  • To access an element within a tuple, chain index operators: data[index][tuple_index].
  • Think about what immutable means and why tuples cannot be changed after creation.
python
Output (expected)
Second person: Bob
Third person's age: 28
[('Alice', 25), ('Bob', 30), ('Charlie', 28), ('Diana', 27)]

Key Takeaways

  1. Lists and tuples are both ordered collections in Python, but lists are mutable (can be changed) while tuples are immutable (cannot be changed).
  2. Both lists and tuples use zero-based indexing to access elements, and you can chain indices to access nested elements.
  3. Nested lists and tuples preserve their structure—they are not flattened. Each inner collection is a single element in the outer collection.
  4. Use lists when you need a collection that can grow, shrink, or change. Use tuples when you need a constant collection or when you need to use the collection as a dictionary key.
  5. Understanding the difference between mutability and immutability is crucial for writing correct Python code and avoiding unexpected errors.

Key Takeaways

  • Lists are mutable, ordered collections created with square brackets; tuples are immutable, ordered collections created with parentheses.
  • Both use zero-based indexing to access elements, and nested structures preserve their hierarchy without flattening.
  • The immutability of tuples makes them suitable for use as dictionary keys and for protecting data from accidental modification.
  • Choose lists for data that needs to change and tuples for data that should remain constant.
  • Common mistakes include attempting to modify tuples, forgetting that list assignment creates a reference rather than a copy, and misunderstanding single-element tuple syntax.