Understanding List Comprehension in Python

List comprehension offers a shorter syntax to create new lists based on existing lists. It can include conditions and expressions.

Basic List Comprehension

Example: Creating a List of Squares

# Basic list comprehension
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print("Squares:", squares)

Output

Squares: [1, 4, 9, 16, 25]

Explanation: The list comprehension [x**2 for x in numbers] creates a new list containing the squares of the numbers.

List Comprehension with Condition

Example: Filtering Even Numbers

# List comprehension with condition
even_numbers = [x for x in numbers if x % 2 == 0]
print("Even Numbers:", even_numbers)

Output

Even Numbers: [2, 4]

Explanation: The condition if x % 2 == 0 filters the list to include only even numbers.