Review your understanding of Python for loops with structured questions. Cover essential topics like iteration, range, nested loops, and loop control in Python programming.
A Python for loop iterates over items in any sequence (list, tuple, string, etc.) or other iterable object. The basic syntax is: `for item in iterable:` followed by an indented block of code. The loop variable (item) takes each value from the iterable in sequence.
["Basic loop: `for fruit in ['apple', 'banana', 'cherry']: print(fruit)`", "With range: `for i in range(5): print(i)`"]
📘 Related Topics:
The range() function generates a sequence of numbers, commonly used for looping a specific number of times. It can take 1-3 arguments: start (inclusive), stop (exclusive), and step size. range() is memory efficient as it generates numbers on demand rather than storing them all.
["range(5) → 0, 1, 2, 3, 4", "range(2, 6) → 2, 3, 4, 5", "range(0, 10, 2) → 0, 2, 4, 6, 8"]
📘 Related Topics:
Common iterables include: - Sequences: lists, tuples, strings - Dictionaries (iterates over keys by default) - Sets - File objects (iterates lines) - Generator expressions - range() objects Any object implementing the iterator protocol can be used.
["String: `for char in 'hello': ...`", "Dictionary: `for key in my_dict:` or `for key, value in my_dict.items():`", "File: `for line in open('file.txt'): ...`"]
📘 Related Topics:
Nested loops are loops within loops, where each iteration of the outer loop triggers a complete run of the inner loop. Common uses include: - Processing multi-dimensional data (matrices, tables) - Generating combinations/permutations - Comparing all elements between collections - Implementing algorithms like bubble sort
["Matrix processing: `for row in matrix: for cell in row: ...`", "Combinations: `for x in range(3): for y in range(3): print(x,y)`"]
📘 Related Topics:
List comprehensions provide a concise way to create lists by applying an expression to each item in an iterable. They are essentially a compact syntax for transforming one list into another using a for loop. They can include conditional logic and multiple for clauses (nested loops).
["Basic: `squares = [x**2 for x in range(10)]`", "With condition: `evens = [x for x in nums if x%2==0]`", "Nested: `pairs = [(x,y) for x in range(3) for y in range(3)]`"]
📘 Related Topics:
Tutorials, Roadmaps, Bootcamps & Visualization Projects