0
0
Pythonprogramming~5 mins

Basic list comprehension syntax in Python

Choose your learning style9 modes available
Introduction
List comprehension helps you create new lists quickly and clearly by writing a simple expression instead of a longer loop.
When you want to make a new list by changing each item in an existing list.
When you want to pick only certain items from a list based on a rule.
When you want to write shorter and easier-to-read code instead of using loops.
When you want to do simple math or operations on each item in a list.
When you want to create a list from another list in one line.
Syntax
Python
new_list = [expression for item in old_list if condition]
The expression is what you want each new item to be.
The condition is optional and filters which items to include.
Examples
Create a list of squares from the original list.
Python
numbers = [1, 2, 3, 4]
squares = [number * number for number in numbers]
Create a list of only even numbers from the original list.
Python
numbers = [1, 2, 3, 4]
even_numbers = [number for number in numbers if number % 2 == 0]
If the original list is empty, the new list will also be empty.
Python
empty_list = []
result = [item for item in empty_list]
Works with a list that has only one item.
Python
single_item_list = [5]
doubled = [item * 2 for item in single_item_list]
Sample Program
This program creates a list of squares from numbers, then filters to keep only even squares.
Python
numbers = [1, 2, 3, 4, 5]
print("Original list:", numbers)
squares = [number * number for number in numbers]
print("Squares:", squares)
even_squares = [square for square in squares if square % 2 == 0]
print("Even squares:", even_squares)
OutputSuccess
Important Notes
List comprehension runs faster than a for-loop for creating lists.
It uses more memory if the list is very large because it creates the whole list at once.
Avoid complex expressions inside list comprehension to keep code readable.
Summary
List comprehension is a short way to make new lists from old lists.
You can add a condition to pick only some items.
It makes your code cleaner and easier to understand.