Welcome to the “List Comprehensions” tutorial!
Overview
List comprehensions provide a concise way to create lists using a single line of code.
Syntax
[expression for item in iterable if condition]
Example
# Squares of even numbers from 0 to 9
squares = [x * x for x in range(10) if x % 2 == 0]
print(squares) # [0, 4, 16, 36, 64]
Key Takeaways
- Compact syntax replaces loops and
append()
. - You can include an optional
if
clause for filtering. - Improves readability for simple list transformations.
Happy coding!
Comments
Post a Comment