List Comprehension

List comprehension is a short and powerful way to create lists in Python.
It allows you to generate a new list by writing a single line of code instead of using multiple lines with a loop.

It makes your code cleaner, shorter, and more readable.

BASIC SYNTAX

[expression for item in iterable]

expression → What you want to store in the list
item → Variable representing each element
iterable → Sequence like list, range, string, etc.

EXAMPLE 1: SIMPLE LIST CREATION

Using normal loop:

squares = []
for x in range(5):
squares.append(x * x)print(squares)

Using list comprehension:

squares = [x * x for x in range(5)]
print(squares)

Both give the same result.

LIST COMPREHENSION WITH CONDITION

You can add an if condition.

even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)

This creates a list of even numbers.

USING IF-ELSE IN LIST COMPREHENSION

result = ["Even" if x % 2 == 0 else "Odd" for x in range(5)]
print(result)

This checks each number and labels it as Even or Odd.

LIST COMPREHENSION WITH STRINGS

word = "Python"
letters = [letter for letter in word]
print(letters)

NESTED LIST COMPREHENSION

matrix = [[j for j in range(3)] for i in range(3)]
print(matrix)

This creates a 3×3 matrix.

WHY USE LIST COMPREHENSION

• Makes code shorter
• Improves readability
• Faster than traditional loops in many cases
• Easy to apply conditions

IMPORTANT POINTS

• Keep it simple for readability
• Avoid very complex nested comprehensions
• Useful for transforming and filtering data

Understanding list comprehension helps you write efficient and professional Python code.

Home » PYTHON INTERMEDIATE (PYI) > Data Structures > List Comprehension