PYTHON LANGUAGE & SYNTAX · BATCH 3
10 · Comprehensions
Comprehensions provide a short way to create collections from existing data.
Most commonly used
list comprehensiondictionary comprehensionset comprehension
Normal loop
products = ["Copper", "Aluminum", "Nickel"]
upper_products = []
for product in products:
upper_products.append(product.upper())List comprehension
upper_products = [product.upper() for product in products]Both create:
["COPPER", "ALUMINUM", "NICKEL"]01
List Comprehension
A list comprehension creates a new list from another iterable.
Basic syntax:
[new_value for item in collection]Example:
numbers = [1, 2, 3, 4]
doubled = [number * 2 for number in numbers]Result:
[2, 4, 6, 8]02
Transform Values
products = ["Copper", "Aluminum", "Nickel"]
upper_products = [
product.upper()
for product in products
]Result:
["COPPER", "ALUMINUM", "NICKEL"]Each product is converted to uppercase.
03
Filter with if
A comprehension can keep only items that match a condition.
Syntax:
[item for item in collection if condition]Example:
quantities = [5, 10, 20, 3, 50]
large_orders = [
quantity
for quantity in quantities
if quantity >= 10
]Result:
[10, 20, 50]04
Transform + Filter
products = [
"Copper",
"Aluminum",
"Nickel",
"Copper"
]
result = [
product.upper()
for product in products
if product != "Nickel"
]Result:
["COPPER", "ALUMINUM", "COPPER"]05
if / else in Comprehension
A conditional expression can choose different output values.
Syntax:
[value_if_true if condition else value_if_false
for item in collection]Example:
quantities = [5, 20, 8, 50]
sizes = [
"Large" if quantity >= 10 else "Small"
for quantity in quantities
]Result:
["Small", "Large", "Small", "Large"]06
Dictionary Comprehension
Creates a dictionary using key-value pairs.
Syntax:
{key: value for item in collection}Example:
products = ["Copper", "Aluminum", "Nickel"]
product_lengths = {
product: len(product)
for product in products
}Result:
{
"Copper": 6,
"Aluminum": 8,
"Nickel": 6
}07
Dictionary Comprehension from Dictionary
prices = {
"Copper": 8500,
"Aluminum": 2300,
"Nickel": 16000
}
high_prices = {
product: price
for product, price in prices.items()
if price > 8000
}Result:
{
"Copper": 8500,
"Nickel": 16000
}08
Set Comprehension
Creates a set, automatically keeping unique values.
products = [
"Copper",
"Aluminum",
"Copper",
"Nickel"
]
unique_products = {
product
for product in products
}Result:
{"Copper", "Aluminum", "Nickel"}09
Nested Comprehension
matrix = [
[1, 2],
[3, 4]
]
numbers = [
number
for row in matrix
for number in row
]Result:
[1, 2, 3, 4]The comprehension reads values from nested lists.
10
When to Use Comprehensions
Use comprehensions when:
the operation is simplethe result is easy to understandyou are creating a new collection
Prefer a normal loop when:
there are many stepsthere are many conditionsreadability becomes worse
Example:
prices = [price * 1.1 for price in prices]Less readable:
Do not create long, complex comprehensions with many nested conditions.