2 min read•june 24, 2024
comprehensions in Python offer a concise way to create new lists based on existing ones. They combine the power of loops, statements, and data transformation into a single line of code, making your programs more efficient and readable.
These versatile tools allow you to filter elements, apply complex transformations, and even work with nested loops. By mastering list comprehensions, you'll streamline your code and enhance your ability to manipulate data effectively in Python.
[[expression](https://www.fiveableKeyTerm:Expression) [for](https://www.fiveableKeyTerm:for) item in iterable [if](https://www.fiveableKeyTerm:If) condition]
expression
transforms each item in the iterableitem
represents each element in the iterableiterable
is the source list or iterable objectif condition
filters which items are includedsquares = [[]](https://www.fiveableKeyTerm:[]) for i in range(1, 6): squares.append(i ** 2)
squares = [i ** 2 for i in range(1, 6)]
list1
and list2
)
combinations = [(x, y) for x in list1 for y in list2]
if
clause after for
loopnumbers
)
even_numbers = [] for num in numbers: if num % 2 == 0: even_numbers.append(num)
even_numbers = [num for num in numbers if num % 2 == 0]
words
)
len()
function:
word_lengths = [] for word in words: word_lengths.append(len(word))
word_lengths = [len(word) for word in words]
expression_if_true if condition else expression_if_false
numbers
)
result = [x ** 2 if x % 2 == 0 else x ** 3 for x in numbers]