A
list
comprehension
is an alternative to repeated calls to
append
.
oldPrices = [ #a list of floats
10.00,
20.00,
30.00
]
#Inflate the price of each item by 6 percent.
newPrices = [1.06 * price for price in oldPrices]
for price in newPrices:
print(f"${price:5.2f}")
$10.60 $21.20 $31.80
A
set
comprehension
is an alterative to repeated calls to
add
.
oldFurniture = { #a set of strings
"chair",
"table",
"bed"
}
newFurniture = {item.capitalize() for item in oldFurniture}
for item in newFurniture:
print(item)
Table Chair Bed
A
dict
comprehension
is an alternative to repeated calls to
update
.
oldPrices = { #a dictionary
"chair": 10.00,
"table": 20.00,
"bed": 30.00
}
#Inflate the price of each item by 6 percent.
newPrices = {key.capitalize(): 1.06 * value for key, value in oldPrices.items()}
for key, value in newPrices.items():
print(f"{key:5} ${value:5.2f}")
Chair $10.60 Table $21.20 Bed $31.80