List Comprehensions in Python Code
List comprehensions in Python provide a concise way to create lists. They consist of a single line of code that can replace the need for a more verbose loop structure. Here's a general format:
Python Code
[expression for item in iterable if condition]
Examples
Basic List Comprehension
Create a list of squares for numbers from 0 to 9:
Python Code
squares = [x**2 for x in range(10)]
# Result: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
List Comprehension with a Condition
Create a list of even numbers from 0 to 9:
Python Code
evens = [x for x in range(10) if x % 2 == 0]
# Result: [0, 2, 4, 6, 8]
List Comprehension with Multiple Iterables
Create a list of Cartesian product pairs:
Python Code
pairs = [(x, y) for x in range(3) for y in range(3)]
# Result: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
List Comprehension with Functions
Apply a function to each element:
Python Code
words = ['hello', 'world', 'Python Code']
lengths = [len(word) for word in words]
# Result: [5, 5, 6]
Nested List Comprehension
Flatten a 2D list:
Python Code
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [item for row in matrix for item in row]
# Result: [1, 2, 3, 4, 5, 6, 7, 8, 9]
List comprehensions can make your code more readable and concise, but it's important to use them wisely to avoid overly complex or hard-to-read expressions.
Top of Form