Python Lesson 11: Lists
A list stores multiple values in a single variable, in order. Lists are the most commonly used data structure in Python.
Creating Lists
fruits = ["apple", "banana", "cherry"]
scores = [95, 87, 92, 78, 100]
empty = []
print(fruits) # ['apple', 'banana', 'cherry']
print(len(fruits)) # 3 — number of items
Accessing Items (Indexing)
fruits = ["apple", "banana", "cherry", "date"]
# 0 1 2 3
print(fruits[0]) # apple (first item)
print(fruits[1]) # banana
print(fruits[-1]) # date (last item)
print(fruits[-2]) # cherry (second from end)
Slicing
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[3:]) # [40, 50, 60]
print(numbers[::2]) # [10, 30, 50] — every 2nd item
Modifying Lists
fruits = ["apple", "banana", "cherry"]
fruits.append("date") # add to end
fruits.insert(1, "avocado") # insert at index 1
fruits.remove("banana") # remove by value
popped = fruits.pop() # remove and return last item
fruits[0] = "mango" # change existing item
print(fruits)
Useful List Methods
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort() # sort in place
numbers.reverse() # reverse in place
print(sum(numbers)) # 31
print(min(numbers)) # 1
print(max(numbers)) # 9
print(numbers.count(1)) # 2 — count occurrences
print(numbers.index(5)) # find index of value
Looping with enumerate()
scores = [85, 92, 78, 95, 88]
for i, score in enumerate(scores):
print(f"Student {i+1}: {score}")
🏋️ Practice Task
Create a list of 5 exam scores. Calculate and print: (1) highest score, (2) lowest score, (3) average score, (4) how many scores are above 80.
💡 Hint: Use max(), min(), sum()/len() for stats. For count above 80: loop and count with if score > 80: count += 1