Episode 21 of 29
List Comprehensions
Learn the elegant Pythonic way to create lists using list comprehensions.
List comprehensions provide a concise way to create lists in Python.
Basic Syntax
# Traditional way
squares = []
for x in range(10):
squares.append(x ** 2)
# List comprehension
squares = [x ** 2 for x in range(10)]With Conditionals
# Even numbers only
evens = [x for x in range(20) if x % 2 == 0]
# Even/odd labels
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]String Comprehensions
names = ["alice", "bob", "charlie"]
capitalized = [name.upper() for name in names]