List Comprehensions
List comprehensions offer a concise and elegant way to create lists based on existing sequences or iterables. They are significantly faster and more readable than standard for loops for list creation.
Standard for Loop vs. Comprehension
Goal: Create a list of squares for numbers 0 through 4.
Using a Standard Loop
python squares = [] for i in range(5): squares.append(i ** 2) print(squares) # [0, 1, 4, 9, 16]
Using a List Comprehension (Recommended)
Syntax: [expression for item in iterable]
python squares_comp = [i ** 2 for i in range(5)] print(squares_comp) # [0, 1, 4, 9, 16]
Example: String Transformations
python names = ['alice', 'bob', 'charlie']
Capitalize all names
capitalized = [name.capitalize() for name in names] print(capitalized) # ['Alice', 'Bob', 'Charlie']