Programming in Python · Lesson 8
Lists — Programming Examples
Five runnable Python examples covering list indexes, traversal, sentinel input, list functions and methods, list comprehension, two-dimensional lists, and dictionaries.
Use these short, runnable examples as demonstration checkpoints. Ask students to predict the output before you run each one.
- List basics: indexes, len(), changing elements, and traversal
# Two ways to create an empty list
waitlist = list()
roster = []
print("Empty lists:", waitlist, roster)
# A nonempty list: the first element is at index 0
temps = [61, 58, 72, 75, 68]
print("All temps:", temps)
print("First day:", temps[0])
print("Fourth day:", temps[3])
print("Last day:", temps[-1])
print("Second to last:", temps[-2])
print("Number of days:", len(temps))
# Change one element with an assignment statement
temps[1] = 60
print("After correction:", temps)
# Index-based traversal: i gives you the position
for i in range(len(temps)):
print("Day", i + 1, "was", temps[i])
# Element-based traversal: simpler, but it can only read the values
for element in temps:
print(element)
# Changing every element requires the index-based loop
for i in range(len(temps)):
temps[i] += 1
print("Each day plus 1:", temps)
# Remove the # on the next line to see an IndexError
# print(temps[5])
Teaching point: A list is a composite data structure that is heterogeneous, ordered, and basically infinite. Indexes start at 0, so the last index in a five-element list is 4, not 5, and negative indexes count from the back. Index-based traversal uses range(len(temps)) and gives you the position; element-based traversal is simpler but can only read values, so changing every element requires the index-based loop. Remove the # on the last line to show an IndexError, then ask which index would have been valid.
- Sentinel input and list functions: quiz scores
# Sentinel-controlled input: append until the user enters -1
scores = []
print("Enter quiz scores, or -1 to quit:")
score = int(input())
while score != -1:
scores.append(score)
score = int(input())
print("Scores:", scores)
# Search the long way: a loop and a counter
hundreds = 0
for element in scores:
if element == 100:
hundreds += 1
print("Perfect scores (loop):", hundreds)
# The same search with the count() method
print("Perfect scores (count):", scores.count(100))
# Sum the long way: a loop and an accumulator
total = 0
for element in scores:
total += element
print("Total (loop):", total)
# The same sum with the sum() function
print("Total (sum):", sum(scores))
print("Average:", sum(scores) / len(scores))
print("Lowest:", min(scores))
print("Highest:", max(scores))
print("Highest is at index:", scores.index(max(scores)))
# sort() changes the list itself
scores.sort()
print("Sorted:", scores)
Build sequence:
- Start with the empty list and the sentinel while-loop, then print the list.
- Add the counter loop, then replace it with scores.count(100) and show that the answers match.
- Add the accumulator loop, then replace it with sum(scores).
- Add min(), max(), index(), and sort(), and point out that sort() is the only one that changes the list.
Teaching point: append() adds one element to the end of a list, which is how a list grows at runtime. Use a known amount (a for-loop with range) when the user knows how many items there are, and a sentinel value when they do not. Test with 100, 85, 100, 92, -1. Then run it with -1 right away: the division and min() fail on an empty list, which is a good lead-in to validating before you calculate.
- List comprehension: mapping and filtering
# A for-loop that appends, then the same list with a comprehension
numbers = []
for i in range(5):
numbers.append(i)
print("Loop:", numbers)
numbers_lc = [i for i in range(5)]
print("Comprehension:", numbers_lc)
prices = [12, 45, 8, 30, 22]
# Filtering: keep only the elements that meet a condition
under_25 = [price for price in prices if price < 25]
print("Under $25:", under_25)
# Mapping: apply a statement to every element
doubled = [price * 2 for price in prices]
print("Doubled:", doubled)
# Mapping and filtering together: half price for items over $20
sale = [price * 0.5 for price in prices if price > 20]
print("Sale prices:", sale)
# join() glues strings together, so numbers must be mapped to strings first
names = ["pen", "notebook", "folder"]
print(", ".join(names))
print(", ".join([str(price) for price in prices]))
Teaching point: A list comprehension puts the for-loop logic inside the square brackets. Filtering adds an if at the end to keep only some elements, mapping changes the expression at the front to transform each element, and the two can be combined. join() only works on strings: remove str() from the last line to show the TypeError, then explain that the comprehension makes a string copy of each number. Have students rewrite the sale line as a for-loop with an if-statement and append().
- Two-dimensional lists: quiz grid and seating chart
# Nested square brackets: a list that contains lists
quiz_scores = [[90, 85, 77],
[72, 88, 95]]
# Two indexes: row first, then column
print("Row 1, column 2:", quiz_scores[1][2])
print("The whole grid:", quiz_scores)
# A nested loop visits every cell: outer for rows, inner for columns
for r in range(len(quiz_scores)):
for c in range(len(quiz_scores[r])):
print(quiz_scores[r][c], end=" ")
print()
# Build a seating chart from an empty list
rows = int(input("How many rows? "))
columns = int(input("How many seats per row? "))
seats = []
for r in range(rows):
seats.append([])
for c in range(columns):
seats[r].append("-")
# Change one cell
pick_row = int(input("Row to reserve: "))
pick_seat = int(input("Seat to reserve: "))
seats[pick_row][pick_seat] = "X"
# join() and a comprehension print the grid one row per line
print("\n".join(["|".join(row) for row in seats]))
Teaching point: A two-dimensional list is a list that contains lists, referenced by row and then column. Traversing one takes a nested loop: the outer loop controls the rows and the inner loop controls the columns, and end=” “ keeps a row on one line until print() ends it. When building from empty, seats.append([]) has to come first, because seats[r] does not exist until that inner list is added. Run it with 2, 3, 1, 2. Then enter a row of 5 to show that the IndexError applies here too.
- Dictionaries: bookstore inventory
# Each entry is a key and a value, inside curly braces
stock = {"notebook": 12,
"pen": 40,
"folder": 7}
print(stock)
print("Pens:", stock["pen"])
# keys() gives you every key, in a sequence you can join or loop over
print("Items:", ", ".join(stock.keys()))
# Assignment updates an existing key, or adds a new one
item = input("Item to set: ")
amount = int(input("New count: "))
stock[item] = amount
# Loop over the keys and use each key to get its value
total = 0
for key in stock.keys():
print("Item, count:", key + ",", stock[key])
total += stock[key]
print("Total items:", total)
# Remove the # on the next line to see a KeyError
# print(stock["pencil"])
Teaching point: A dictionary stores key and value pairs in curly braces and looks up values by key instead of by a numbered index. Assigning to a key that exists updates its value, and assigning to a new key adds an entry, so each key appears only once. keys() returns an iterative sequence you can join or loop over, and stock[key] gets each value. Run it with pen and 25 (update), then stapler and 3 (add). Remove the # on the last line to show a KeyError: reading a missing key is an error, but assigning to one is not.
Exit-ticket prompts
- In the list [4, 8, 15, 16, 23], what are the values at index 2 and index -1?
- Why does Example 1 use an index-based loop to add 1 to every element?
- Write a list comprehension that keeps only the even numbers in a list named values.
- In Example 4, which cell does seats[1][0] refer to?
- What is the difference between print(stock[“pencil”]) and stock[“pencil”] = 3 when “pencil” is not a key?
Answer key
- 15 and 23.
- An element-based loop can only read values. Changing an element requires its index.
- evens = [x for x in values if x % 2 == 0]
- The second row, first seat.
- The print statement causes a KeyError. The assignment adds a new entry.
Course Notes