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)]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
The format of list comprehension follows the format
y = [expression for element in iterable]
- expression is a valid expression that returns a value. In the example, the expression 2 * i returns a value doubles the input
- element is the object or value in the iterable (e.g. list). In the example, the member value is i.
- iterable is a list, set, or any object that can return its elements one at a time. In the example above, the iterable is range(10).
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)
final_prices = [21.4, 32.1, 42.8, 74.9, 96.3, 26.8]