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
number = [1, 2, 3, 4, 5, 6, 7, 8, 9]
oddnumber = [x for x in number if x%2 != 0]
print (oddnumber)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)One list comprehension inside another, usually for working with:
- nested lists (matrix)
- multiple loops
- flattening lists
num []
for i in range (5):
for j in range (3):
print(num[i, j])num = [(i, j) for i in range (5) for j in range (3)]
print(num)table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
print(table)
Simple Way to Understand
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
