66. List Comprehensions
List Comprehensions: Creating lists in a concise, readable way
1. Basic List Comprehension
# Traditional for-loop
squares = []
for i in range(5):
squares.append(i**2)
# List comprehension
squares = [i**2 for i in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]2. List Comprehension with Conditional Logic
# List of even numbers from 0 to 9
evens = [i for i in range(10) if i % 2 == 0]
print(evens) # Output: [0, 2, 4, 6, 8]3. Applying Transformation with List Comprehension
4. List Comprehension with Multiple Iterators
5. Nested List Comprehensions
6. List Comprehension with Functions
7. List Comprehension with Conditional Expressions
8. List Comprehension for Filtering Even Numbers
9. Creating a List of Tuples
10. List Comprehension for Dictionary Keys
Summary of Features:
Last updated