Concepts / Lists and Tuples

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

Why Multiple Values Need a Home

Imagine you need to store a shopping list, a sequence of measurements, or a collection of names. You could create separate variables for each item, but that quickly becomes unwieldy. Python provides built-in data structures designed to hold multiple objects together. The two most fundamental of these are lists and tuples. While they seem similar on the surface, they have a crucial difference that makes each one suited to different tasks.

What Lists and Tuples Are

A list is an ordered collection of items enclosed in square brackets, where each item can be of any type. A tuple is also an ordered collection of items, but it is enclosed in parentheses. Both structures allow you to store multiple objects and access them by their position. The critical distinction is that lists are mutable—you can change, add, or remove items after creation—while tuples are immutable, meaning once created, they cannot be modified.

Tuples are used to hold together multiple objects. Think of them as similar to lists, but without the extensive functionality that the list class gives you. One major feature of tuples is that they are immutable like strings—you cannot modify tuples.

How Indexing Locates Elements

Both lists and tuples use the same indexing mechanism to access individual elements. You specify the item's position within square brackets using zero-based indexing, meaning the first item is at position 0, the second at position 1, and so on. This works identically for lists and tuples, so the syntax and logic are the same regardless of which structure you are using.

animalsdog[1]cat[2]bird[3]fish
How are elements stored in memory, and how does indexing locate them?

In the diagram above, the list animals contains four items. To access the third item (bird), you would use animals[2]. The index always refers to the position in the sequence, starting from zero. This same principle applies to tuples.

Nested Structures: Lists and Tuples Within Lists and Tuples

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. As far as Python is concerned, they are just objects stored using another object. When you nest structures, you can access deeply nested items by chaining index operations.

containscontainscontainscontainscontainscontainscontainszoo[0]dog[1][0]cat[1]list: cat, lion[1][1]lion[2]tuple: bird, fish[2][0]bird[2][1]fish
What does it look like when lists or tuples contain other lists or tuples?

To access the third item in the third item of the new_zoo tuple, you would specify new_zoo[2][2]. This chaining of index operations works because each index operation returns the object at that position, and if that object is itself a list or tuple, you can index into it again.

The Mutability Divide: Lists vs. Tuples in Action

The most important practical difference between lists and tuples is mutability. Let's trace through what happens when you try to modify each one.

What do you think happens?

You have a list called fruits = ['apple', 'banana', 'cherry'] and a tuple called colors = ('red', 'blue', 'green'). What do you think happens when you try to change the second item in each? For example, fruits[1] = 'orange' and colors[1] = 'yellow'?

  • Both succeed and the items are changed
  • Both fail with an error
  • The list succeeds but the tuple fails with an error
  • The tuple succeeds but the list fails with an error
Reveal answer

Answer: The list succeeds but the tuple fails with an error

Lists are mutable, so you can assign a new value to any position. Tuples are immutable, so any attempt to modify them raises a TypeError. This is the fundamental distinction between the two structures.

fruits[1] = 'orange'colors[1] = 'yellow'fruits = ['apple','banana', 'cherry']colors = ('red','blue', 'green')fruits = ['apple','orange', 'cherry']TypeError: 'tuple'object does notsupport itemassignment
What happens when I try to modify a list versus a tuple, and why do they behave differently?

When to Use Lists and When to Use Tuples

Use a list when you need a collection that may change—when you might add, remove, or modify items. Lists are flexible and provide many built-in methods for manipulation. Use a tuple when you want to ensure that a collection of items remains constant. Tuples are also useful as dictionary keys (lists cannot be keys) and are slightly more memory-efficient than lists.

  • Use lists for shopping lists, to-do items, or any collection that grows or shrinks
  • Use tuples for fixed data like coordinates (x, y), RGB color values, or function return values that should not be accidentally modified
  • Use tuples as dictionary keys when you need a composite key
  • Use tuples when passing immutable collections to functions that should not modify the original data

Common Mistakes with Lists and Tuples

  • Forgetting that indexing starts at zero

    Python uses zero-based indexing, so the first item is always at index 0, the second at index 1, and so on

    Fix: Remember: the index is always one less than the position. The first item is at index 0, the second at index 1, etc.

  • Attempting to modify a tuple

    Tuples are immutable by design. Once created, their contents cannot be changed

    Fix: If you need to modify the collection, use a list instead. If you need a modified version of a tuple, create a new tuple

  • Confusing the syntax for creating lists and tuples

    Lists use square brackets [] and tuples use parentheses (). Using the wrong syntax creates the wrong data type

    Fix: Remember: lists are [like this], tuples are (like this)

  • Not understanding nested indexing

    Each index operation returns an element; if that element is itself a list or tuple, you can index into it again, but you must understand the structure

    Fix: Trace through the structure step by step: nested_list[2] gets the third item, then [1] gets the second item within that, then [0] gets the first item within that

Worked Example: Building and Accessing a Zoo Inventory

Accessing Items in a Nested Zoo Structure

You are building a zoo inventory system. You have a list called zoo that contains the name of the zoo as the first item, and then a tuple of animals as the second item. The animals tuple contains three items: a string for the first animal, a list of two animals for the second item, and a tuple of two animals for the third item. You need to access the second animal in the list that is stored as the second item in the animals tuple.

Understand the structure: zoo = ['My Zoo', ('dog', ['cat', 'lion'], ('bird', 'fish'))] — The structure is: a list containing a string and a tuple. The tuple contains a string, a list, and a tuple.

Identify the path to the target: We want the second animal in the list that is the second item in the animals tuple. The animals tuple is at zoo[1]. The list of animals is at zoo[1][1]. The second animal in that list is at zoo[1][1][1].

Trace through the indices: zoo[1] returns the tuple ('dog', ['cat', 'lion'], ('bird', 'fish')). zoo[1][1] returns the list ['cat', 'lion']. zoo[1][1][1] returns 'lion'.

Verify the result: The value at zoo[1][1][1] is 'lion', which is indeed the second animal in the list that is stored as the second item in the animals tuple.

zoo[1][1][1] = 'lion'

Understanding the Four Built-in Data Structures

Python provides four built-in data structures: lists, tuples, dictionaries, and sets. Each serves a different purpose. Lists and tuples are ordered collections accessed by position. Dictionaries are unordered collections accessed by key. Sets are unordered collections of unique items with no indexing. Understanding when to use each one is essential for writing efficient and clear code.

includesincludestypetypetypetypePython DataStructuresOrdered CollectionsListmutable, indexedUnordered CollectionsTupleimmutable, indexedDictionarykey-value pairsSetunique items
What are the four data structures, and how do they relate to each other in terms of use cases?

Practice: Working with Lists and Tuples

MEDIUM

Create a list called inventory that contains three items: a string 'warehouse', a tuple of three product names, and a list of three quantities. Then write out the index expressions needed to access: the second product name in the tuple, the third quantity in the list, and the first product name. Finally, try to modify the second product name in the tuple and observe what happens.

Hints
  • Remember that lists use square brackets and tuples use parentheses
  • The tuple is at index 1 in the inventory list, and the list of quantities is at index 2
  • To access the second product name, you need to chain two index operations: first to get the tuple, then to get the item within it
  • When you try to modify the tuple, Python will raise a TypeError because tuples are immutable

Key Takeaways

Lists and tuples are both ordered collections that allow you to store multiple items and access them by position using zero-based indexing. The fundamental difference is that lists are mutable—you can change, add, or remove items—while tuples are immutable and cannot be modified after creation. Both can contain nested structures, allowing you to build complex hierarchies of data. Understanding when to use each one—lists for dynamic collections and tuples for fixed, protected data—is essential for writing effective Python code. Remember that Python provides four built-in data structures in total: lists, tuples, dictionaries, and sets, each with its own purpose and use cases.

Key Takeaways

  • Lists are mutable ordered collections enclosed in square brackets; tuples are immutable ordered collections enclosed in parentheses
  • Both lists and tuples use zero-based indexing to access elements, and both support nested structures
  • Use lists when you need to modify a collection; use tuples when you need a fixed, unchangeable collection or a dictionary key
  • Attempting to modify a tuple raises a TypeError because tuples are immutable by design
  • Python provides four built-in data structures: lists, tuples, dictionaries, and sets, each suited to different tasks