Module 6: Practice Problems
15 problems to reinforce your understanding of Python lists. Try to solve each problem before looking at the hints and solutions!
Problem 1: Create and Print
EasyCreate a list called weekdays containing the five weekday names (Monday through Friday). Print the list, the first day, and the last day.
Use square brackets to create the list. Access the first element with index 0, and the last with index -1.
weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] print(weekdays) print("First day:", weekdays[0]) print("Last day:", weekdays[-1])
Problem 2: List Length and Membership
EasyGiven colors = ["red", "green", "blue", "yellow", "purple"], print the number of colors and check whether "orange" and "blue" are in the list.
Use len() for the count and the in operator for membership checking.
colors = ["red", "green", "blue", "yellow", "purple"] print("Number of colors:", len(colors)) print("orange in list:", "orange" in colors) print("blue in list:", "blue" in colors)
Problem 3: Building a List
EasyStart with an empty list called shopping. Add "milk", "eggs", and "bread" using append(). Then insert "butter" at the beginning. Print the final list.
Use insert(0, item) to add at the beginning.
shopping = [] shopping.append("milk") shopping.append("eggs") shopping.append("bread") shopping.insert(0, "butter") print(shopping) # Output: ['butter', 'milk', 'eggs', 'bread']
Problem 4: Remove and Pop
EasyGiven fruits = ["apple", "banana", "cherry", "banana", "date"], remove the first "banana" using remove(). Then pop the last item and print what was removed. Print the final list.
remove() deletes the first matching value. pop() without arguments removes and returns the last item.
fruits = ["apple", "banana", "cherry", "banana", "date"] fruits.remove("banana") removed = fruits.pop() print("Removed:", removed) print("Final list:", fruits) # Removed: date # Final list: ['apple', 'cherry', 'banana']
Problem 5: Sorting
EasyGiven scores = [78, 92, 45, 88, 67, 95, 73], sort the list in ascending order and print it. Then sort it in descending order and print it.
Use sort() for ascending and sort(reverse=True) for descending.
scores = [78, 92, 45, 88, 67, 95, 73] scores.sort() print("Ascending:", scores) scores.sort(reverse=True) print("Descending:", scores)
Problem 6: Basic Slicing
MediumGiven numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], use slicing to print: (a) the first 4 elements, (b) elements from index 3 to 7, (c) the last 3 elements.
Use [:4], [3:7], and [-3:] respectively.
numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] print("First 4:", numbers[:4]) print("Index 3 to 7:", numbers[3:7]) print("Last 3:", numbers[-3:])
Problem 7: Step Slicing
MediumGiven alphabet = list("abcdefghijklmnopqrstuvwxyz"), use slicing to print: (a) every other letter, (b) every third letter, (c) the alphabet in reverse.
Use step values: [::2], [::3], and [::-1].
alphabet = list("abcdefghijklmnopqrstuvwxyz") print("Every other:", alphabet[::2]) print("Every third:", alphabet[::3]) print("Reversed:", alphabet[::-1])
Problem 8: Safe Copy
MediumCreate a list original = [1, 2, 3, 4, 5]. Make a copy using slicing. Append 99 to the copy. Verify the original is unchanged by printing both lists.
Use original[:] to create an independent copy.
original = [1, 2, 3, 4, 5] copy = original[:] copy.append(99) print("Original:", original) # [1, 2, 3, 4, 5] print("Copy:", copy) # [1, 2, 3, 4, 5, 99]
Problem 9: Basic Comprehension
MediumUse a list comprehension to create a list of the squares of numbers from 1 to 10.
Syntax: [expression for variable in range()]
squares = [n ** 2 for n in range(1, 11)] print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Problem 10: Filtered Comprehension
MediumGiven numbers = list(range(1, 21)), use a list comprehension to create a new list containing only the numbers divisible by 3.
Add if n % 3 == 0 at the end of the comprehension.
numbers = list(range(1, 21)) divisible_by_3 = [n for n in numbers if n % 3 == 0] print(divisible_by_3) # [3, 6, 9, 12, 15, 18]
Problem 11: String List Processing
MediumGiven names = [" alice ", "BOB ", " Charlie", " diana "], use a list comprehension to create a cleaned list where each name is stripped of whitespace and title-cased.
Chain .strip().title() in the expression part of the comprehension.
names = [" alice ", "BOB ", " Charlie", " diana "] clean = [name.strip().title() for name in names] print(clean) # ['Alice', 'Bob', 'Charlie', 'Diana']
Problem 12: Count and Index
MediumGiven grades = ["A", "B", "A", "C", "B", "A", "D", "B", "A"], find how many A's there are and the index of the first "D".
Use .count("A") and .index("D").
grades = ["A", "B", "A", "C", "B", "A", "D", "B", "A"] print("Number of A's:", grades.count("A")) print("First D at index:", grades.index("D")) # Number of A's: 4 # First D at index: 6
Problem 13: Comprehension with if/else
HardGiven temps = [58, 72, 85, 45, 90, 68, 32, 77], use a list comprehension to create a list of labels: "hot" if temperature >= 80, "warm" if >= 60, or "cold" otherwise.
Use nested ternary: "hot" if t >= 80 else "warm" if t >= 60 else "cold" in the expression.
temps = [58, 72, 85, 45, 90, 68, 32, 77] labels = ["hot" if t >= 80 else "warm" if t >= 60 else "cold" for t in temps] print(labels) # ['cold', 'warm', 'hot', 'cold', 'hot', 'warm', 'cold', 'warm']
Problem 14: Combine Two Lists
HardGiven list_a = [1, 3, 5, 7, 9] and list_b = [2, 4, 6, 8, 10], create a new combined list, sort it, then use slicing to get the middle three elements.
Use + or extend() to combine. After sorting, calculate start index for middle three.
list_a = [1, 3, 5, 7, 9] list_b = [2, 4, 6, 8, 10] combined = list_a + list_b combined.sort() print("Combined sorted:", combined) mid = len(combined) // 2 middle_three = combined[mid - 1 : mid + 2] print("Middle three:", middle_three) # Middle three: [5, 6, 7]
Problem 15: List Processing Challenge
HardGiven a list of scores scores = [88, 45, 92, 67, 100, 55, 73, 81, 49, 96]:
- Use a comprehension to get only passing scores (>= 60)
- Sort the passing scores in descending order
- Find how many students failed
- Calculate the average of all scores (use
sum()andlen())
Use [s for s in scores if s >= 60] for filtering. Failing count = total - passing count. Average = sum(scores) / len(scores).
scores = [88, 45, 92, 67, 100, 55, 73, 81, 49, 96] # 1. Passing scores passing = [s for s in scores if s >= 60] print("Passing:", passing) # 2. Sort descending passing.sort(reverse=True) print("Sorted descending:", passing) # 3. Failing count failing_count = len(scores) - len(passing) print("Students who failed:", failing_count) # 4. Average average = sum(scores) / len(scores) print(f"Average score: {average}")