Discover how to store collections of data in a single variable using lists.
Imagine you are packing for a trip to Mars. Would you rather carry 50 individual bags, or one organized backpack with 50 labeled pockets? In Python, lists are that backpack—allowing you to store hundreds of items in a single variable!
A list is a collection of items stored in a specific order. Instead of creating ten different variables for ten players, you create one list. In Python, we define a list using square brackets `[]` and separate items with commas. Every item in a list has a specific position called an index. Crucially, Python is a 'zero-indexed' language, meaning we start counting at rather than . If a list has items, the positions are numbered from to .
1. Create a list: `tools = ["Hammer", "Drill", "Saw"]` 2. To get the first item, use `tools[0]`, which is "Hammer". 3. To get the second item, use `tools[1]`, which is "Drill". 4. The index of the last item is .
Quick Check
If a list called 'colors' has 5 items, what is the index number of the very first item?
Answer
0
Lists are mutable, which is a fancy way of saying they can be changed after they are created. You can replace an item by assigning a new value to a specific index. To grow your list, use the `.append()` method to add an item to the very end. If you want to put an item in a specific spot, use `.insert(index, value)`. This shifts all other items to the right, increasing their index numbers by .
1. Start with `quests = ["Find Map", "Cross River"]` 2. Change the first quest: `quests[0] = "Find Key"`. Now the list is `["Find Key", "Cross River"]`. 3. Add a new quest to the end: `quests.append("Enter Castle")`. 4. The list now has items.
Quick Check
Which Python method would you use to add 'Pizza' to the very end of a list named 'food'?
Answer
food.append("Pizza")
Sometimes you need to clean up. The `.pop()` method removes an item at a specific index (and 'pops' it back to you), while `.remove("item_name")` searches for a specific value and deletes it. To know how big your collection is, use the `len()` function. This returns the total count of items. If `len(my_list)` equals , then the highest valid index you can use is .
1. You have scores: `scores = [150, 200, 300, 50]`. 2. Remove the lowest score at the end: `scores.pop(3)`. 3. Find how many scores remain: `count = len(scores)`. 4. Since `count` is now , the items are at indices .
What is the output of `len(["A", "B", "C"])`?
If `players = ["Alice", "Bob", "Charlie"]`, what is `players[1]`?
The .append() method adds an item to the beginning of a list.
Review Tomorrow
In 24 hours, try to explain to a friend why the last item in a list of 10 items is at index 9 and not index 10.
Practice Activity
Create a list of your top 3 favorite video games. Use .append() to add a 4th, then use len() to print how many games are now in your list.