Peer
uest
List comprehensions is a elegant way of making lists with one line of code. Consider the following example
doubles = [2 * i for i in range(10)]
print(doubles)
Output
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
The format of list comprehension follows the format
y = [expression for element in iterable]
Below is a more complex example
def calc_final_price(price, sales_tax):
return price * (1 + sales_tax)
list_prices = [20, 30, 40, 70, 90, 25]
final_prices = [calc_final_price(x, 0.07) for x in list_prices]
print('final_prices = ', final_prices)
Output
final_prices = [21.4, 32.1, 42.8, 74.9, 96.3, 26.8]