Lists

6. Lists#

Hide code cell source

import sys
from pathlib import Path

current = Path.cwd()
for parent in [current, *current.parents]:
    if (parent / '_config.yml').exists():
        project_root = parent  # ← Add project root, not chapters
        break
else:
    project_root = Path.cwd().parent.parent

sys.path.insert(0, str(project_root))

from shared import thinkpython, diagram, jupyturtle, download

# Register as top-level modules so direct imports work in subsequent cells
sys.modules['thinkpython'] = thinkpython
sys.modules['diagram'] = diagram
sys.modules['jupyturtle'] = jupyturtle
sys.modules['download'] = download

This chapter presents one of Python’s most useful built-in types, lists. You will also learn more about objects and what can happen when multiple variables refer to the same object.

Learning Objectives

By the end of this chapter, you should be able to:

  • Construct and manipulate Python lists using indexing, slicing (including advanced step slices), and core list methods.

  • Explain and reason about object identity, aliasing, shallow vs. deep copies, and how lists behave when passed to functions.

  • Use lists idiomatically in Python: list comprehensions, unpacking and starred expressions, enumerate(), zip(), and basic sorting/looping patterns.

Introduction to Lists

What is a List?

If you’re familiar with other programming languages, Python lists are similar to arrays in languages like Java, C++, or JavaScript. However, Python lists are more flexible: they can grow or shrink dynamically and can contain mixed data types.

A Python list is a sequence data type, like strings and tuples. Sequences are:

  • ordered collections that support

  • indexing,

  • slicing,

  • len(), in membership testing, and

  • iteration.

The key distinction is mutability and heterogeneous element data types:

  • In a string, the values are characters; in a list, they can be any type. The value literals in a list are called elements.

  • Lists are mutable, meaning they can be modified after creation.

The following figure shows the state diagram for fruits, numbers and empty. Lists are objects in Python’s memory. When you create a list, Python creates a list object that holds your data in a specific order, and the variable holds a reference to that object.

numbers = [42, 123]
fruits = ['apple', 'banana', 'cherry']
empty = []
../../_images/0de68897ec4447306fa3b9a686883ecc1e01ad141980a8bf241ecd191f98387b.png