For Loop vs List Comprehension: Which is Better?
Both for loops and list comprehensions are used to iterate over sequences, but they have key differences in performance, readability, and use cases.
1. Key Differences
Feature | For Loop | List Comprehension |
---|---|---|
Performance | Slower (due to explicit looping) | Faster (optimized in C) |
Readability | More readable for complex logic | Concise for simple operations |
Memory Usage | Can be more efficient with generators | Creates a new list in memory |
Best For | Complex logic, multiple operations | Simple transformations and filtering |
2. Example Comparisons
Basic Example: Squaring Numbers
Using For Loop
numbers = [1, 2, 3, 4, 5]
squared = []
for num in numbers:
squared.append(num ** 2)
print(squared)
🔹 Output: [1, 4, 9, 16, 25]
Using List Comprehension
numbers = [1, 2, 3, 4, 5]
squared = [num ** 2 for num in numbers]
print(squared)
✅ More concise and faster!
3. Performance Comparison
For large datasets, list comprehensions are much faster because they run at C-speed internally.
Speed Test
import time
numbers = list(range(1000000))
# For Loop
start = time.time()
squared_loop = []
for num in numbers:
squared_loop.append(num ** 2)
end = time.time()
print("For Loop Time:", end - start)
# List Comprehension
start = time.time()
squared_list_comp = [num ** 2 for num in numbers]
end = time.time()
print("List Comprehension Time:", end - start)
✅ **List comprehension is around 30-40% faster than a for loop!
4. When to Use For Loop vs List Comprehension
✔️ Use For Loop When:
- You have complex logic (multiple conditions, nested loops).
- You need to modify elements conditionally.
- You want better readability for long operations.
✔️ Use List Comprehension When:
- You need a quick transformation of a list.
- The operation is simple and easy to read.
- You need better performance for large data.
5. Which is Better?
👉 For simple operations → List Comprehension (faster, cleaner)
👉 For complex logic → For Loop (easier to read, debug)
🚀 Best Practice: Use list comprehension for simple tasks and for loops for complex ones!