Section Overview
In this section, you’ll learn how to work with lists, one of Python’s most useful data structures. Lists allow you to store multiple items in a single variable, making it easier to organize and manage data.
By the end of this section, you should be able to:
- Create and manipulate lists
- Access list items using indexing
- Use common list methods to add, remove, and modify items
- Iterate over lists with loops
Lesson 1: Creating Lists
A list is created by placing items inside square brackets, separated by commas.
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits)
Output:
['apple', 'banana', 'cherry']
Lists can hold items of different types, but usually contain related data:
mixed = [1, "two", 3.0, True]
Lesson 2: Accessing Items by Index
List items have positions, starting at 0.
Example:
colors = ["red", "green", "blue"]
print(colors[0]) # Outputs: red print(colors[2]) # Outputs: blue
Negative indexes count from the end:
print(colors[-1]) # Outputs: blue
Lesson 3: Common List Methods
append(item)
– add an item to the endinsert(index, item)
– insert an item at a specific positionremove(item)
– remove the first occurrence of an itempop()
– remove and return the last itemlen(list)
– get the number of items
Example:
numbers = [10, 20, 30]
numbers.append(40)
numbers.insert(1, 15)
numbers.remove(20)
last = numbers.pop()
print(numbers) # Outputs: [10, 15, 30] print(last) # Outputs: 40 print(len(numbers)) # Outputs: 3
Lesson 4: Looping Through Lists
You can loop through all items in a list using a for
loop:
names = ["Alice", "Bob", "Charlie"]
for name in names:
print("Hello, " + name)
This prints a personalized greeting for each name.
Quiz: Check Your Understanding
1. What index does the first item in a list have?
Answer: 0
2. Which method adds an item to the end of a list?
Answer: append()
3. What does this code print?
items = [1, 2, 3]
print(items[-2])
Answer: 2
4. True or False: Lists can contain items of different data types.
Answer: True
Practice Exercise: Shopping List
Create a program that:
- Starts with an empty shopping list (an empty list)
- Asks the user to enter three items to add to the shopping list
- Adds each item to the list
- Prints the final shopping list
Starter code:
shopping_list = []
for i in range(3):
item = input("Enter an item to add to the shopping list: ")
shopping_list.append(item)
print("Your shopping list:", shopping_list)
Challenge: Let the user enter items until they type "done".