- Explain why a data structure like a list is necessary in programming.
- Define a "list" as an ordered, mutable collection of items.
- Use square bracket syntax
[]to create a new list.
The Problem with Single Variables
Imagine you wanted to store a list of your favourite movies. With the tools we have so far, it would be very clumsy:
movie1 = "The Matrix"
movie2 = "Dune"
movie3 = "Blade Runner 2049"
# ... what if you have 100 favourite movies? This is a nightmare!
We need a better way to store and manage a collection of related items. The solution is a data structure, and Python's most common and useful one is the list.
What is a List?
A list is a single variable that can hold an ordered collection of multiple items. Key features are:
- Ordered: The items are stored in a specific sequence that doesn't change.
- Mutable: You can change the list after it's created—add items, remove items, or change existing items.
- Flexible: A single list can hold different data types (though it's most common to have a list of all the same type).
The Syntax: Square Brackets []
We create lists using square brackets, with individual items separated by commas.
# An empty list
shopping_list = []
# A list of strings
favourite_movies = ["The Matrix", "Dune", "Blade Runner 2049"]
# A list of integers
high_scores = [1050, 980, 875, 800]
# A mixed-type list (less common, but possible)
mixed_list = ["Hello", 100, True]
Knowledge Check: Test Your Syntax!
Before you start experimenting, let's see if you can spot a correctly formatted list. Try the interactive activity below.
Live Example: Creating Lists
Now, see the code in action. The Trinket below defines and prints a few different lists. Run it, then follow the "Your Turn" instructions to create your own list!
A list is like a multi-pocket folder for your data. You now have a way to store a whole collection of items in a single, organized place. In the next lesson, we'll learn how to get items out of the list.
Interactive Sandbox
Use this space to practice writing code and complete the "Your Turn" activities above.