Skip to content

script_22.py - List Comprehension with Loop

Code

Python
#!/usr/bin/env python3
"""List comprehension with loop"""

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [x**2 for x in numbers]

print("Original:", numbers)
print("Squares:", squares)

Explanation

Line 4: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - List of integers

Line 5: squares = [x**2 for x in numbers] - List comprehension: creates new list in one line - Syntax: [expression for variable in iterable] - x is loop variable (iterates through numbers) - x**2 is the expression (applied to each element) - ** is exponentiation operator - Equivalent to:

Python
squares = []
for x in numbers:
    squares.append(x**2)
- More concise and Pythonic than explicit loop - Returns new list type - squares contains [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Line 7-8: Print statements - Shows both original and transformed lists - Demonstrates list comprehension didn't modify original