โก Python List Comprehension Examples
List comprehensions are Python's elegant one-liner loops. Write cleaner, faster code with this powerful feature.
List comprehensions are 30-50% faster than equivalent for-loops in Python benchmarks.
๐ป Code Example:
# Basic list comprehension squares = [x**2 for x in range(10)] print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # With condition (filter) evens = [x for x in range(20) if x % 2 == 0] print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] # Nested list comprehension (flatten a 2D list) matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flat = [num for row in matrix for num in row] print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9] # String transformation pynfinity_users = ['santoshtvk', 'dhruv', 'tvk'] upper_users = [user.upper() for user in pynfinity_users] print(upper_users) # ['SANTOSHTVK', 'DHRUV', 'TVK']
| Concept | Key Takeaway |
|---|---|
| [expr for x in iterable] | Basic comprehension โ transform every element |
| [expr for x in iterable if condition] | Filter comprehension โ only include matching items |
| [expr for x in outer for y in inner] | Nested comprehension โ flattening 2D structures |
| {k: v for k,v in dict.items()} | Dict comprehension โ same concept for dictionaries |
Keep exploring and happy coding! ๐