List comprehension is used to create new lists quickly and clearly. It makes code shorter and easier to read compared to using loops.
0
0
Why list comprehension is used in Python
Introduction
When you want to make a new list by changing each item in an existing list.
When you want to filter items from a list based on a condition.
When you want to write simple list creation in one line instead of many lines.
When you want your code to be clean and easy to understand.
When you want to avoid writing extra lines for loops and appending items.
Syntax
Python
new_list = [expression for item in old_list if condition]
The expression is what you want to put in the new list for each item.
The if condition part is optional and filters which items to include.
Examples
This creates a list of squares of each number.
Python
numbers = [1, 2, 3, 4, 5] squares = [x * x for x in numbers]
This creates a list of only even numbers by filtering.
Python
numbers = [1, 2, 3, 4, 5] even_numbers = [x for x in numbers if x % 2 == 0]
If the original list is empty, the new list is also empty.
Python
empty_list = [] result = [x for x in empty_list]
Works fine even if the list has only one item.
Python
single_item = [10] doubled = [x * 2 for x in single_item]
Sample Program
This program shows how to create a list of squares and a list of even numbers from the original list using list comprehension.
Python
numbers = [1, 2, 3, 4, 5] print("Original list:", numbers) squares = [number * number for number in numbers] print("Squares using list comprehension:", squares) even_numbers = [number for number in numbers if number % 2 == 0] print("Even numbers using list comprehension:", even_numbers)
OutputSuccess
Important Notes
List comprehension is faster than using a for loop with append because it is optimized internally.
It uses more memory if the list is very large, so for huge data sets, consider using generators.
Common mistake: forgetting the brackets [] which makes it a generator expression, not a list.
Summary
List comprehension helps write shorter and clearer code to create lists.
It can both transform and filter items in one simple line.
It is a beginner-friendly way to work with lists efficiently.