Friday, May 22, 2026

Python Tutorial for Intermediate: List Comprehension

We have completed the Beginner series in Python language, and we are now dive in Intermediate-level chapters. If you haven't read the beignner chapters yet, read them first so that you understand this chapter even better.

What is a List Comprehension?

List comprehension is a concise way to write code that generates lists in a single line, instead of using multiple lines with loops. It is powerful, readable, and easy to understand for simple operations. In short "We create a new list by iterating over an old list".

However, when you have multiple nested loops or complex conditions, list comprehensions can become hard to read and understand.

Syntax: new_list = [expression for item in iterable]

Note: List use [ ] bracket.

Example - Without Comprehension

num = [1, 2, 3, 4, 5]
square = []
for x in num:
  square.append(x**2)
print(square)

Example - With List Comprehension

square = [x**2 for x in range(1, 6)]
print(square)

List Comprehension with Condition

We can also filter items using "if" statement.
Syntax: new_list = [expression for item in iterable if condition]
Example: Find ODD numbers
number = [1, 2, 3, 4, 5, 6, 7, 8, 9]
oddnumber = [x for x in number if x%2 != 0]
print (oddnumber)
Using if-else
if-else condition is also used in list comprehension but it changes the output value.
Syntax: new_list = [true_expr if condition else false_expr for item in interable]

Example: Even / Odd
number = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_odd = ["even" if x%2==0 else "odd" for x in number]
print(even_odd)
Nested List comprehension

One list comprehension inside another, usually for working with:

  • nested lists (matrix)
  • multiple loops
  • flattening lists
Simple nested list
Normal loop:
num []
for i in range (5):
for j in range (3):
print(num[i, j])
With list comrehension:
num = [(i, j) for i in range (5) for j in range (3)]
print(num)
Matrix : Only 2D support
matrix = [[1,2] [3, 4][5, 6]]
output = [num for row in matrix for num in row]
print(output)
Create Multiplication Table
table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
print(table)

Simple Way to Understand

[a for b in x for a in b]
means
for b in x:
    for a in b:

Using Functions Inside Comprehension

words = ["hello", "world", "python"]
lengths = [len(word) for word in words]
print(lengths)

When NOT to Use List Comprehension

This is a very helpful and powerful but it also make a problem when:

  • Logic becomes too complex
  • Readability suffers
  • Multiple nested conditions get messy
Read More: Python OOPs

Practics

Task 1: Find Even Numbers using List Comprehension
Task 2: Append value in list using comprehension

🐍 Python Playground

No comments:

Post a Comment

Featured Post

What Is Artificial Intelligence (AI) ? – A Step-by-Step Guide

AI (Artificial Intelligence) is a rapidly growing technology in today's world, and you can see it whenever you browse or search for any ...