List comprehensions in Python are a concise way to create lists. They allow you to generate a new list by iterating over an existing one and applying conditions or transformations. 🧠
Basic Syntax
A simple list comprehension follows this structure:
[expression for item in iterable]
Example:
squares = [x**2 for x in range(10)]
# Equivalent to:
squares = []
for x in range(10):
squares.append(x**2)
👉 Explore more about Python loops to deepen your understanding.
Advanced Techniques
- Nested List Comprehensions:
matrix = [[row[i] for row in [[1,2,3],[4,5,6],[7,8,9]]] for i in range(3)]
- Conditional Filters:
even_squares = [x**2 for x in range(10) if x % 2 == 0]
- Combining with Functions:
[len(word) for word in "hello world".split()]
Use Cases
- Data cleaning: Filter and transform datasets efficiently.
- Generating sequences: Create lists of numbers, strings, or objects.
- Simplifying code: Replace verbose loops with one-liners.
💡 Check out this visual guide on list comprehensions for interactive examples.
For further learning, visit our Python Advanced Features section! 🚀