Use python list comprehension to simplify your code
Peer uest
Cancel
Forget passwd??
blog
27
Use python list comprehension to simplify your code

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]
1. expression is a valid expression that returns a value. In the example, the expression 2 * i returns a value doubles the input
2. element is the object or value in the iterable (e.g. list). In the example, the member value is i.
3. 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)


Output

final_prices =  [21.4, 32.1, 42.8, 74.9, 96.3, 26.8]