Lists
As programs grow beyond toy examples, we quickly need ways to work with groups of related values. Real programs rarely deal with a single number or string in isolation. Lists are Python’s simplest and most common way to keep related data together, and they show up everywhere in practical code, including the data structures we use to generate pages, process files, and manage program state.
What a list is and when to use one
A list is an ordered collection of values stored under a single name. Each value in the list has a position, and that order is preserved.
We use a list when we want to keep multiple related values together and treat them as a group. For example, a list is a natural fit for storing the names of planets, a set of filenames to generate, or a sequence of HTML fragments that will later be combined.
planets = ["Mercury", "Venus", "Earth", "Mars"]
Creating lists with literal syntax
Lists are created using square brackets, with values separated by commas. This is called list literal syntax.
The values in a list do not have to be unique, and they are written in the order we want to keep.
moons = ["Phobos", "Deimos"]
Accessing list elements by index
Each element in a list is accessed by its index. Indexes start at zero, not one.
We refer to an element by writing the list name followed by the index in square brackets.
first_planet = planets[0]
This gives us the first item stored in the list.
Adding and removing elements from a list
Lists can change over time. We can add new elements or remove existing ones as the program runs.
To add an element to the end of a list, we use append. To remove a specific value, we use remove.
planets.append("Jupiter")
planets.remove("Mars")
These operations modify the list directly.
Using lists to store multiple related values
Once values are in a list, we can pass the list around as a single object. This makes functions simpler and data easier to manage.
For example, we might store page titles in a list before generating HTML output.
titles = ["Mercury", "Venus", "Earth"]
html = "<ul>"
for title in titles:
html += f"<li>{title}</li>"
html += "</ul>"
The list lets us treat a collection of related values as one meaningful unit.
Conclusion
We introduced lists as ordered collections that group related values together. We saw how to create them, access their contents, and modify them as a program runs. With this foundation, lists become a natural building block for representing real program data in a clear and structured way.