|
| 1 | +""" |
| 2 | +list_comprehension_example.py |
| 3 | +
|
| 4 | +A beginner-friendly tutorial on Python list comprehensions. |
| 5 | +
|
| 6 | +List comprehensions are a concise way to create lists in Python. |
| 7 | +They're more readable and often faster than equivalent for loops. |
| 8 | +""" |
| 9 | + |
| 10 | +# ============================================================================ |
| 11 | +# 1. BASIC LIST COMPREHENSION |
| 12 | +# ============================================================================ |
| 13 | + |
| 14 | +print("=" * 60) |
| 15 | +print("1. BASIC LIST COMPREHENSION") |
| 16 | +print("=" * 60) |
| 17 | + |
| 18 | +# Traditional way with a for loop: |
| 19 | +numbers = [] |
| 20 | +for i in range(5): |
| 21 | + numbers.append(i * 2) |
| 22 | +print(f"Traditional way: {numbers}") |
| 23 | + |
| 24 | +# List comprehension way (much more concise!): |
| 25 | +numbers = [i * 2 for i in range(5)] |
| 26 | +print(f"List comprehension: {numbers}") |
| 27 | + |
| 28 | +# Syntax: [expression for item in iterable] |
| 29 | +# - expression: what to do with each item (i * 2) |
| 30 | +# - item: the variable name (i) |
| 31 | +# - iterable: what to iterate over (range(5)) |
| 32 | + |
| 33 | + |
| 34 | +# ============================================================================ |
| 35 | +# 2. LIST COMPREHENSION WITH STRINGS |
| 36 | +# ============================================================================ |
| 37 | + |
| 38 | +print("\n" + "=" * 60) |
| 39 | +print("2. LIST COMPREHENSION WITH STRINGS") |
| 40 | +print("=" * 60) |
| 41 | + |
| 42 | +words = ["hello", "world", "python"] |
| 43 | +upper_words = [word.upper() for word in words] |
| 44 | +print(f"Original: {words}") |
| 45 | +print(f"Uppercase: {upper_words}") |
| 46 | + |
| 47 | +# Get the length of each word |
| 48 | +word_lengths = [len(word) for word in words] |
| 49 | +print(f"Word lengths: {word_lengths}") |
| 50 | + |
| 51 | + |
| 52 | +# ============================================================================ |
| 53 | +# 3. LIST COMPREHENSION WITH CONDITIONAL FILTERING |
| 54 | +# ============================================================================ |
| 55 | + |
| 56 | +print("\n" + "=" * 60) |
| 57 | +print("3. LIST COMPREHENSION WITH CONDITIONAL FILTERING") |
| 58 | +print("=" * 60) |
| 59 | + |
| 60 | +# Traditional way: filter even numbers |
| 61 | +numbers = list(range(10)) |
| 62 | +even_numbers = [] |
| 63 | +for num in numbers: |
| 64 | + if num % 2 == 0: |
| 65 | + even_numbers.append(num) |
| 66 | +print(f"Traditional way (even numbers): {even_numbers}") |
| 67 | + |
| 68 | +# List comprehension way: |
| 69 | +even_numbers = [num for num in range(10) if num % 2 == 0] |
| 70 | +print(f"List comprehension (even numbers): {even_numbers}") |
| 71 | + |
| 72 | +# Syntax: [expression for item in iterable if condition] |
| 73 | +# Only items that satisfy the condition are included |
| 74 | + |
| 75 | + |
| 76 | +# ============================================================================ |
| 77 | +# 4. CONDITIONAL EXPRESSIONS (TERNARY OPERATOR) |
| 78 | +# ============================================================================ |
| 79 | + |
| 80 | +print("\n" + "=" * 60) |
| 81 | +print("4. CONDITIONAL EXPRESSIONS (TERNARY OPERATOR)") |
| 82 | +print("=" * 60) |
| 83 | + |
| 84 | +# Transform values based on a condition |
| 85 | +numbers = list(range(10)) |
| 86 | +# If number is even, keep it; if odd, multiply by 10 |
| 87 | +transformed = [num if num % 2 == 0 else num * 10 for num in numbers] |
| 88 | +print(f"Original: {numbers}") |
| 89 | +print(f"Transformed (even stays, odd * 10): {transformed}") |
| 90 | + |
| 91 | +# Syntax: [value_if_true if condition else value_if_false for item in iterable] |
| 92 | + |
| 93 | + |
| 94 | +# ============================================================================ |
| 95 | +# 5. NESTED LIST COMPREHENSIONS |
| 96 | +# ============================================================================ |
| 97 | + |
| 98 | +print("\n" + "=" * 60) |
| 99 | +print("5. NESTED LIST COMPREHENSIONS") |
| 100 | +print("=" * 60) |
| 101 | + |
| 102 | +# Create a multiplication table (2D list) |
| 103 | +multiplication_table = [[i * j for j in range(1, 6)] for i in range(1, 6)] |
| 104 | +print("Multiplication table (5x5):") |
| 105 | +for row in multiplication_table: |
| 106 | + print(row) |
| 107 | + |
| 108 | +# Flatten a 2D list |
| 109 | +matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] |
| 110 | +flattened = [num for row in matrix for num in row] |
| 111 | +print(f"\nOriginal matrix: {matrix}") |
| 112 | +print(f"Flattened: {flattened}") |
| 113 | + |
| 114 | +# Read nested comprehensions from left to right: |
| 115 | +# [num for row in matrix for num in row] |
| 116 | +# means: for each row in matrix, for each num in row, include num |
| 117 | + |
| 118 | + |
| 119 | +# ============================================================================ |
| 120 | +# 6. PRACTICAL EXAMPLES |
| 121 | +# ============================================================================ |
| 122 | + |
| 123 | +print("\n" + "=" * 60) |
| 124 | +print("6. PRACTICAL EXAMPLES") |
| 125 | +print("=" * 60) |
| 126 | + |
| 127 | +# Example 1: Extract numbers from a string |
| 128 | +text = "I have 3 cats and 2 dogs" |
| 129 | +numbers = [int(char) for char in text if char.isdigit()] |
| 130 | +print(f"Text: '{text}'") |
| 131 | +print(f"Numbers found: {numbers}") |
| 132 | + |
| 133 | +# Example 2: Square only positive numbers |
| 134 | +numbers = [-2, -1, 0, 1, 2, 3, 4] |
| 135 | +squared_positives = [num ** 2 for num in numbers if num > 0] |
| 136 | +print(f"\nOriginal: {numbers}") |
| 137 | +print(f"Squared positives: {squared_positives}") |
| 138 | + |
| 139 | +# Example 3: Create a list of tuples |
| 140 | +names = ["Alice", "Bob", "Charlie"] |
| 141 | +name_lengths = [(name, len(name)) for name in names] |
| 142 | +print(f"\nNames: {names}") |
| 143 | +print(f"Name-length pairs: {name_lengths}") |
| 144 | + |
| 145 | +# Example 4: Filter and transform |
| 146 | +temperatures = [20, 25, 30, 15, 35, 10] |
| 147 | +hot_days = [f"{temp}°C" for temp in temperatures if temp >= 25] |
| 148 | +print(f"\nTemperatures: {temperatures}") |
| 149 | +print(f"Hot days (>=25°C): {hot_days}") |
| 150 | + |
| 151 | + |
| 152 | +# ============================================================================ |
| 153 | +# 7. COMPARISON: FOR LOOP vs LIST COMPREHENSION |
| 154 | +# ============================================================================ |
| 155 | + |
| 156 | +print("\n" + "=" * 60) |
| 157 | +print("7. COMPARISON: FOR LOOP vs LIST COMPREHENSION") |
| 158 | +print("=" * 60) |
| 159 | + |
| 160 | +# Task: Get squares of even numbers from 0 to 9 |
| 161 | + |
| 162 | +# Method 1: Traditional for loop |
| 163 | +result1 = [] |
| 164 | +for num in range(10): |
| 165 | + if num % 2 == 0: |
| 166 | + result1.append(num ** 2) |
| 167 | +print(f"For loop: {result1}") |
| 168 | + |
| 169 | +# Method 2: List comprehension (more Pythonic!) |
| 170 | +result2 = [num ** 2 for num in range(10) if num % 2 == 0] |
| 171 | +print(f"List comprehension: {result2}") |
| 172 | + |
| 173 | +# Both produce the same result, but list comprehension is: |
| 174 | +# - More concise (one line vs multiple lines) |
| 175 | +# - More readable (once you understand the syntax) |
| 176 | +# - Often faster (Python optimizes list comprehensions) |
| 177 | + |
| 178 | + |
| 179 | +# ============================================================================ |
| 180 | +# 8. COMMON PATTERNS AND TIPS |
| 181 | +# ============================================================================ |
| 182 | + |
| 183 | +print("\n" + "=" * 60) |
| 184 | +print("8. COMMON PATTERNS AND TIPS") |
| 185 | +print("=" * 60) |
| 186 | + |
| 187 | +# Pattern 1: Simple transformation |
| 188 | +original = [1, 2, 3, 4, 5] |
| 189 | +doubled = [x * 2 for x in original] |
| 190 | +print(f"Doubled: {doubled}") |
| 191 | + |
| 192 | +# Pattern 2: Filtering |
| 193 | +numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
| 194 | +evens = [x for x in numbers if x % 2 == 0] |
| 195 | +print(f"Even numbers: {evens}") |
| 196 | + |
| 197 | +# Pattern 3: Filter and transform |
| 198 | +words = ["python", "java", "c++", "javascript", "go"] |
| 199 | +long_words = [word.upper() for word in words if len(word) > 4] |
| 200 | +print(f"Long words (uppercase): {long_words}") |
| 201 | + |
| 202 | +# Pattern 4: Multiple conditions |
| 203 | +numbers = list(range(20)) |
| 204 | +filtered = [x for x in numbers if x % 2 == 0 and x % 3 == 0] |
| 205 | +print(f"Numbers divisible by both 2 and 3: {filtered}") |
| 206 | + |
| 207 | +# Tip: If your list comprehension gets too complex, consider using a for loop |
| 208 | +# Readability is more important than brevity! |
| 209 | + |
| 210 | + |
| 211 | +# ============================================================================ |
| 212 | +# SUMMARY |
| 213 | +# ============================================================================ |
| 214 | + |
| 215 | +print("\n" + "=" * 60) |
| 216 | +print("SUMMARY") |
| 217 | +print("=" * 60) |
| 218 | +print(""" |
| 219 | +List Comprehension Syntax: |
| 220 | + [expression for item in iterable] |
| 221 | + [expression for item in iterable if condition] |
| 222 | + [value_if_true if condition else value_if_false for item in iterable] |
| 223 | +
|
| 224 | +Key Points: |
| 225 | + 1. List comprehensions create new lists |
| 226 | + 2. They're more concise than for loops |
| 227 | + 3. They're often faster than equivalent for loops |
| 228 | + 4. Use them when the logic is simple and readable |
| 229 | + 5. If it gets too complex, use a regular for loop instead |
| 230 | +
|
| 231 | +Remember: Readability counts! Don't sacrifice clarity for brevity. |
| 232 | +""") |
| 233 | + |
0 commit comments