MyInternships.in

Python Data Structures

Python List Comprehension

List comprehension is a compact, readable way to build a new list from an existing iterable in a single line of code.


Basic Syntax

The general form is [expression for item in iterable]. Python evaluates the expression for every item and collects the results into a new list.

A simple comprehension
Python
squares = [n * n for n in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

Filtering With if

Add an if condition at the end to keep only items that pass a test — this replaces a for loop combined with an if statement and an append() call.

Filtering even numbers
Python
nums = range(1, 11)
evens = [n for n in nums if n % 2 == 0]
print(evens)  # [2, 4, 6, 8, 10]

if / else in the Expression

To choose between two values for every item (rather than filtering), place if/else before the for clause.

Conditional expression
Python
labels = ["even" if n % 2 == 0 else "odd" for n in range(5)]
print(labels)

Nested Comprehensions

You can nest comprehensions to flatten a nested list, or use them to build a grid. Keep nesting to one level for readability — beyond that, a regular for loop is usually clearer.

Flattening a nested list
Python
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
print(flat)  # [1, 2, 3, 4, 5, 6]

Comprehension vs a for Loop

A comprehension is shorthand for a for loop that appends to a list — it is not a different feature, just a more concise, often faster syntax for the same job.

Same result, two styles
Python
# Using a for loop
squares = []
for n in range(1, 6):
    squares.append(n * n)

# Using a list comprehension
squares = [n * n for n in range(1, 6)]
💡

Reach for a comprehension when the logic fits on one readable line; switch to a full for loop once you need multiple statements or complex conditions.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships