List Comprehensions
Introduction to List Comprehensions
List comprehensions provide a concise, readable way to create lists based on existing iterables. They're more Pythonic than traditional loops for creating lists and are often faster and more elegant.
List comprehensions combine the power of loops and conditional statements into a single line, making your code more compact and easier to read once you understand the syntax.
Basic Syntax
The basic syntax is: [expression for item in iterable]. This creates a new list by applying the expression to each item in the iterable.
With Conditions
You can add conditions using if to filter items: [expression for item in iterable if condition]
Nested Comprehensions
You can nest comprehensions to create lists of lists or work with nested structures:
When to Use Comprehensions
✅ Use List Comprehensions When:
• Creating a new list from an existing iterable
• The logic is simple and fits on one line
• You want more readable, Pythonic code
• Performance matters (comprehensions are often faster)
💡 Use Traditional Loops When:
• The logic is complex and needs multiple lines
• You need side effects (like printing during iteration)
• Readability would suffer from a comprehension