How to Optimize Loops in Python Using List Comprehension With Examples

  

 

 What Is List Comprehension?

List comprehension is a concise way to create lists using a single line of code, often replacing multi-line for loops. It's faster, cleaner, and more Pythonic.

 Basic Syntax

[expression for item in iterable if condition]

 Traditional Loop vs List Comprehension

 Traditional Loop:

squares = []
for i in range(10):
    squares.append(i * i)

 List Comprehension:

squares = [i * i for i in range(10)]

 Both produce the same result, but list comprehension is shorter and often faster.

 With Conditionals

Add filtering:

evens = [x for x in range(20) if x % 2 == 0]

 Equivalent to filtering with if in a loop.

 Nested Loop Comprehension

pairs = [(x, y) for x in [1, 2] for y in [3, 4]]
# Output: [(1, 3), (1, 4), (2, 3), (2, 4)]

 Real Use Case: Clean Data

data = ["apple", "", "banana", "", "cherry"]
cleaned = [item for item in data if item]

 Removes empty strings efficiently.

 Performance Comparison

import time

start = time.time()
squares = [i * i for i in range(10_000_000)]
print("List comprehension:", time.time() - start)

start = time.time()
squares = []
for i in range(10_000_000):
    squares.append(i * i)
print("Traditional loop:", time.time() - start)

 List comprehension usually performs better due to internal optimizations.

 Summary Table

Feature List Comprehension Traditional Loop
Speed  Faster  Slower
Readability  More concise  More verbose
Memory usage  Similar (for lists)  Similar
Conditional logic  Supported  Supported
Nesting support  Yes  Yes

 When Not to Use List Comprehension

  • Avoid deeply nested or complex logic
  • Avoid side effects (e.g., printing or file writing in list comprehension)
  • Use generator expressions if you don’t need all data in memory

 Best Practice

Use list comprehension when:

  • You’re transforming or filtering data
  • The logic is simple and readable
  • You want compact, Pythonic code

0 Comments:

Post a Comment