Can a list comprehension call a function?


#1

Question

In this exercise, the variable from the list comprehension is used to calculate a value. Is it possible to call a function using the variable?

Answer

Yes, the variable in the for of a list comprehension can be used as a parameter to a function. In this example, the variable number is passed to randint() to calculate a random number between number and 2 * number for the list produced by the comprehension.

from random import randint

random_numbers = [ randint(number, 2 * number) for number in range(10)]

print(random_numbers)