List comprehension is a quick way to create lists. Loops do the same but take more lines. Both help make new lists from old ones.
0
0
List comprehension vs loop in Python
Introduction
When you want to make a new list by changing or filtering items from another list.
When you want your code to be shorter and easier to read.
When you need to do simple operations on each item in a list.
When you want to avoid writing many lines of code for creating lists.
When you want to clearly show how a list is built from another list.
Syntax
Python
### List comprehension syntax: new_list = [expression for item in old_list if condition] ### Loop syntax: new_list = [] for item in old_list: if condition: new_list.append(expression)
List comprehension combines loop and condition in one line.
Loops are more flexible for complex tasks but longer.
Examples
List comprehension to get squares of numbers.
Python
numbers = [1, 2, 3, 4, 5] squares = [n * n for n in numbers]
Loop doing the same as above.
Python
numbers = [1, 2, 3, 4, 5] squares = [] for n in numbers: squares.append(n * n)
List comprehension on empty list returns empty list.
Python
empty_list = [] result = [x for x in empty_list] print(result)
List comprehension with one item doubles it.
Python
single_item = [10] result = [x * 2 for x in single_item] print(result)
Sample Program
This program shows how to get squares of numbers using both loop and list comprehension. Both give the same result.
Python
numbers = [1, 2, 3, 4, 5] # Using loop squares_loop = [] for number in numbers: squares_loop.append(number * number) print("Squares using loop:", squares_loop) # Using list comprehension squares_comp = [number * number for number in numbers] print("Squares using list comprehension:", squares_comp)
OutputSuccess
Important Notes
List comprehension is usually faster than loops because it is optimized internally.
Loops are better when you need multiple steps or complex logic inside.
Common mistake: forgetting to append in loops, which list comprehension handles automatically.
Use list comprehension for simple, clear list creation; use loops for complex tasks.
Summary
List comprehension is a short, readable way to create lists.
Loops are more flexible but take more lines.
Both produce the same results for simple list creation tasks.