Computer Science
Grade 10
20 min
For Loops
For Loops
Tutorial Preview
1
Introduction & Learning Objectives
Learning Objectives
Implement nested for loops to process two-dimensional data structures like matrices or grids.
Construct and use list comprehensions to create new lists from existing iterables concisely.
Iterate over dictionaries using the .keys(), .values(), and .items() methods.
Utilize the enumerate() function to access both the index and value of an item during iteration.
Apply the zip() function to iterate over multiple sequences in parallel.
Analyze and debug common pitfalls in complex loops, such as modifying a list while iterating over it.
Ever wondered how a game renders a 2D map or how a social media app processes a feed of user data? 🗺️ It all comes down to mastering advanced loops!
In this lesson, we'll move beyond basic for loops to explore powerful tec...
2
Key Concepts & Vocabulary
TermDefinitionExample
Nested LoopA loop that is placed inside the body of another loop. The inner loop is executed completely for each single iteration of the outer loop.To print coordinates on a 3x3 grid: for x in range(3): for y in range(3): print(f'({x}, {y})')
List ComprehensionA concise, syntactic way to create a new list by applying an expression to each item in an existing iterable, often including a condition.To create a list of squares for numbers 0-4: `squares = [x**2 for x in range(5)]` results in `[0, 1, 4, 9, 16]`.
IterableAn object capable of returning its members one at a time. Examples include lists, tuples, dictionaries, strings, and range objects.In `for char in 'hello':`, the string 'hello' is the iterable.
enumerate()A built-in function th...
3
Core Syntax & Patterns
Nested Loop Pattern
for outer_variable in outer_iterable:
# Code for outer loop
for inner_variable in inner_iterable:
# Code for inner loop, runs for each outer iteration
Use this pattern for processing 2D data structures like matrices, grids, or lists of lists. The outer loop typically handles rows, and the inner loop handles columns (or elements within each row).
List Comprehension Syntax
new_list = [expression for item in iterable if condition]
A compact alternative to a for loop for creating lists. The `if condition` part is optional and used for filtering elements. It improves code readability for simple transformations.
Dictionary Iteration with .items()
for key, value in my_dictionary.items():
# Code that uses both key and value
This is the...
4 more steps in this tutorial
Sign up free to access the complete tutorial with worked examples and practice.
Sign Up Free to ContinueSample Practice Questions
Challenging
Which of the following is the most concise and Pythonic way to flatten `matrix = [[1, 2], [3, 4], [5, 6]]` into `[1, 2, 3, 4, 5, 6]` using the concepts from the tutorial?
A.flat = []
for i in range(len(matrix)):
flat.extend(matrix[i])
B.flat = [num for row in matrix for num in row]
C.import itertools
flat = list(itertools.chain.from_iterable(matrix))
D.flat = matrix[0] + matrix[1] + matrix[2]
Challenging
Given `list_a = [1, 2, 3, 4]` and `list_b = ['a', 'b']`, what is the output of `list(zip(list_a, list_b))`?
A.ValueError because the lists are of different lengths.
B.[ (1, 'a'), (2, 'b'), (3, None), (4, None) ]
C.[ (1, 'a'), (2, 'b') ]
D.[ (1, 'a'), (2, 'b'), (3, 'a'), (4, 'b') ]
Challenging
You are given two lists: `products = ['apple', 'banana', 'orange']` and `prices = [1.2, 0.8, 1.0]`. Which code snippet correctly creates a dictionary mapping each product to its price?
A.{product: price for price in prices for product in products}
B.{products[i]: prices[i] for i in range(len(products))}
C.dict(zip(products, prices))
D.{product: prices[product] for product in products}
Want to practice and check your answers?
Sign up to access all questions with instant feedback, explanations, and progress tracking.
Start Practicing Free