-
Explanation: Python list comprehensions provide a concise and elegant way to create lists. They allow you to build new lists by applying an expression to each item in an existing iterable (like another list, tuple, or range), optionally filtering items based on a condition. They are often more readable and efficient than traditional
for
loops for list creation. It's a hallmark of Pythonic code. -
Note:
python list comprehension tutorial
,create list python concisely
,filter list python
,transform list python
,python one-liner list
. -
Code Examples:
# Example 1 (Beginner-Friendly): Basic list comprehension (transformation)
# Creates a new list where each number from 0 to 4 is squared.
# Equivalent to: squares = []; for x in range(5): squares.append(x**2)
squares = [x**2 for x in range(5)]
print(f"Squares: {squares}") # Output: [0, 1, 4, 9, 16]
# Example 2 (Slightly More Complex): List comprehension with a condition (filtering)
# Creates a list of only even numbers from 0 to 9.
# Syntax: [expression for item in iterable if condition]
even_numbers = [num for num in range(10) if num % 2 == 0]
print(f"Even numbers: {even_numbers}") # Output: [0, 2, 4, 6, 8]
# Example 3 (Intermediate): Combining transformation and filtering
# Gets the square of only odd numbers from a list.
original_numbers = [1, 2, 3, 4, 5, 6, 7]
odd_squares = [num**2 for num in original_numbers if num % 2 != 0]
print(f"Odd squares: {odd_squares}") # Output: [1, 9, 25, 49]
# Example 4 (Advanced Beginner): List comprehension from strings
# Creates a list of uppercase characters from a string, excluding spaces.
sentence = "Python is awesome"
uppercase_letters = [char.upper() for char in sentence if char.isalpha()]
print(f"Uppercase letters: {uppercase_letters}") # Output: ['P', 'Y', 'T', 'H', 'O', 'N', 'I', 'S', 'A', 'W', 'E', 'S', 'O', 'M', 'E']
# Example 5 (Intermediate): List comprehension with a conditional expression (ternary operator)
# Apply different transformations based on a condition within the expression itself.
# Syntax: [expression_if_true if condition else expression_if_false for item in iterable]
numbers = [1, 2, 3, 4, 5]
parity_status = ["Even" if num % 2 == 0 else "Odd" for num in numbers]
print(f"Parity status: {parity_status}") # Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd']
# Example 6 (Advanced): Nested list comprehensions (for flattened lists or matrix transformations)
# Creating a flattened list from a list of lists.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = [num for row in matrix for num in row]
print(f"Flattened matrix: {flattened_list}") # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Example 7 (Advanced): Creating a new matrix with transformations
# Multiplying each element in a matrix by 2.
transformed_matrix = [[num * 2 for num in row] for row in matrix]
print(f"Transformed matrix: {transformed_matrix}") # Output: [[2, 4, 6], [8, 10, 12], [14, 16, 18]]