Advanced Python Iteration Techniques with Practical Examples
This article presents ten advanced Python iteration techniques—including list, dictionary, and set comprehensions, zip, enumerate, itertools utilities, and generator expressions—each illustrated with clear code examples to help developers write more concise, efficient, and readable code.
Python's advanced iteration techniques can make code more concise, efficient, and readable, covering list, dict, and set comprehensions, the zip and enumerate functions, various itertools utilities, and generator expressions.
Example 1: List comprehension to compute squares
numbers = [1, 2, 3, 4, 5]
</code><code>squares = [num**2 for num in numbers]
</code><code>print(squares) # 输出 [1, 4, 9, 16, 25]Example 2: Dictionary comprehension to create a mapping
keys = ['a', 'b', 'c']
</code><code>values = [1, 2, 3]
</code><code>mapping = {key: value for key, value in zip(keys, values)}
</code><code>print(mapping) # 输出 {'a': 1, 'b': 2, 'c': 3}Example 3: Set comprehension to remove duplicates
items = [1, 2, 2, 3, 4, 4, 5]
</code><code>unique_items = {item for item in items}
</code><code>print(unique_items) # 输出 {1, 2, 3, 4, 5}Example 4: Using zip to iterate over multiple sequences in parallel
names = ["Alice", "Bob", "Charlie"]
</code><code>ages = [25, 30, 35]
</code><code>for name, age in zip(names, ages):
print(f"{name} is {age} years old.")Example 5: Using enumerate to get index and value
fruits = ['apple', 'banana', 'cherry']
</code><code>for index, fruit in enumerate(fruits):
print(f"Item {index}: {fruit}")Example 6: Using itertools.chain to flatten a nested list
from itertools import chain
</code><code>nested_list = [[1, 2], [3, 4], [5]]
</code><code>flat_list = list(chain(*nested_list))
</code><code>print(flat_list) # 输出 [1, 2, 3, 4, 5]Example 7: Using itertools.groupby to group data by a key
from itertools import groupby
</code><code>data = [(1, 'A'), (1, 'B'), (2, 'C'), (2, 'D')]
</code><code>sorted_data = sorted(data, key=lambda x: x[0])
</code><code>grouped_data = {k: list(v) for k, v in groupby(sorted_data, lambda x: x[0])}
</code><code>print(grouped_data) # 输出 {1: [(1, 'A'), (1, 'B')], 2: [(2, 'C'), (2, 'D')]}Example 8: Using itertools.permutations to generate permutations
from itertools import permutations
</code><code>letters = ['A', 'B', 'C']
</code><code>permutations_list = list(permutations(letters))
</code><code>print(permutations_list)Example 9: Using itertools.product to generate Cartesian product
from itertools import product
</code><code>colors = ['Red', 'Blue']
</code><code>sizes = ['Small', 'Large']
</code><code>combinations = list(product(colors, sizes))
</code><code>print(combinations)Example 10: Using a generator expression to save memory
large_numbers = (num for num in range(1000000))
</code><code>sum_of_large_numbers = sum(large_numbers)
</code><code>print(sum_of_large_numbers)These examples demonstrate how advanced iteration techniques in Python can help you write more efficient and concise code; applying them thoughtfully can improve performance while maintaining readability.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
