- Learning Objectives
- Prerequisites
- Introduction
- What is List Comprehension?
- Why is List Comprehension Required?
- Syntax
- Components of List Comprehension
- List Comprehension with Conditions
- Nested List Comprehension
- List Comprehension vs Traditional Loop
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Understand List Comprehension.
- Create lists using concise syntax.
- Use conditions in list comprehensions.
- Use nested list comprehensions.
- Compare list comprehensions with traditional loops.
- Apply list comprehensions in real-world programs.
Before learning this chapter, you should know:
- Lists
- Loops
- Conditional Statements
- Functions
In Python,
creating a list using loops is a common task.
Example:
numbers = []
for i in range(1, 6):
numbers.append(i)Python provides a much shorter and cleaner way to achieve the same result using List Comprehension.
List comprehensions improve readability and reduce the amount of code required to create lists.
A List Comprehension is a concise way to create a new list by iterating over an iterable and optionally applying a condition.
List Comprehension is a one-line method for creating lists.
Without list comprehension,
creating a new list requires multiple lines of code.
With list comprehension,
the same task can often be completed in a single line.
Benefits include:
- Less code
- Better readability
- Faster execution for many simple use cases
- Easy data transformation
[expression for item in iterable][expression for item in iterable if condition]A list comprehension consists of three parts:
Produces the value to be stored.
Represents each element of the iterable.
The collection being traversed.
numbers = [x * x for x in range(1, 6)]
print(numbers)Output
[1, 4, 9, 16, 25]
Example
even = [x for x in range(1,11) if x % 2 == 0]
print(even)Output
[2, 4, 6, 8, 10]
List comprehensions can also be nested.
Example
matrix = [
[i * j for j in range(1,4)]
for i in range(1,4)
]
print(matrix)Output
[[1,2,3],[2,4,6],[3,6,9]]
| Traditional Loop | List Comprehension |
|---|---|
| More lines of code | One-line syntax |
| Uses append() | Creates list directly |
| More verbose | More concise |
| Easier for beginners | Better for simple transformations |
Iterable
↓
Read Element
↓
Apply Expression
↓
Check Condition (Optional)
↓
Add to New List
↓
Repeat
↓
Return Final List
- Less code.
- Better readability.
- Cleaner syntax.
- Faster for many simple operations.
- Easy list creation.
- Not suitable for complex business logic.
- Deep nesting reduces readability.
- Difficult to debug if overly complex.
- Keep comprehensions simple.
- Use meaningful variable names.
- Avoid excessive nesting.
- Use normal loops for complex logic.
- Add conditions only when necessary.
Writing very long list comprehensions.
Using nested comprehensions unnecessarily.
Ignoring readability.
Using list comprehensions when a normal loop is easier to understand.
numbers = [x for x in range(1,6)]
print(numbers)[1, 2, 3, 4, 5]
numbers = [x*x for x in range(1,6)]
print(numbers)[1, 4, 9, 16, 25]
numbers = [x**3 for x in range(1,6)]
print(numbers)[1, 8, 27, 64, 125]
even = [x for x in range(1,11) if x%2==0]
print(even)[2, 4, 6, 8, 10]
odd = [x for x in range(1,11) if x%2!=0]
print(odd)[1, 3, 5, 7, 9]
names = ["python","java","sql"]
result = [name.upper() for name in names]
print(result)['PYTHON', 'JAVA', 'SQL']
names = ["Python","Java","Oracle"]
result = [len(name) for name in names]
print(result)[6, 4, 6]
numbers = [-5,-2,0,4,7]
result = [x for x in numbers if x>0]
print(result)[4, 7]
words = ["Python","Java","SQL"]
result = [word[0] for word in words]
print(result)['P', 'J', 'S']
matrix = [
[i*j for j in range(1,4)]
for i in range(1,4)
]
print(matrix)[[1, 2, 3], [2, 4, 6], [3, 6, 9]]
Iterable
↓
Read Element
↓
Apply Expression
↓
Condition Checked
↓
True?
↓
Add to List
↓
Repeat
↓
Final List
Original List
│
├──1
├──2
├──3
├──4
└──5
↓
List Comprehension
↓
Expression Applied
↓
New List
│
├──1
├──4
├──9
├──16
└──25
- Short syntax.
- Better readability.
- Efficient list creation.
- Supports conditions.
- Supports nested structures.
- Keep expressions simple.
- Avoid deeply nested comprehensions.
- Use descriptive variable names.
- Prefer loops when readability decreases.
- Overcomplicating list comprehensions.
- Ignoring readability.
- Using nested comprehensions excessively.
- Forgetting conditions.
List Comprehension is a concise way to create lists using a single line of code.
[expression for item in iterable]Yes.
Example:
[x for x in range(10) if x % 2 == 0]Yes.
For simple list creation and transformations, list comprehensions often provide a shorter alternative to loops.
Yes.
Nested list comprehensions are supported, but they should be used carefully to maintain readability.
For many simple list-building operations, list comprehensions can be more concise and may perform well, but clarity should be prioritized.
- Less code
- Better readability
- Efficient list creation
- Easy transformations
- Create a list of squares.
- Create a list of cubes.
- Create a list of even numbers.
- Convert names to uppercase.
- Create a multiplication table using nested list comprehension.
- List Comprehension → One-line list creation.
- Syntax →
[expression for item in iterable] - Supports conditions.
- Supports nesting.
- Cleaner than many traditional loops.
In this chapter, we learned:
- List Comprehension
- Syntax
- Components
- Conditional List Comprehension
- Nested List Comprehension
- Practical Programs
- Advantages
- Limitations
- Best Practices
- Common Mistakes
- Interview Questions
- Practice Programs
- Quick Revision