Create a list of numbers with their factorial values
This Python code calculates the factorial of each number in a list using the math.factorial() function from the math module and stores the results in a new list. Here's how the code works:
- import math: This line imports the math module, which contains various mathematical functions, including the factorial() function for calculating factorials.
- numbers = [2, 3, 4, 5]: This line initializes a variable named numbers and assigns it a list containing four numbers.
- factorials = [math.factorial(x) for x in numbers]: This line of code initializes a variable named factorials and assigns it the result of a list comprehension.
- for x in numbers: This part sets up a loop that iterates through each number x in the numbers list.
- math.factorial(x): For each number in the list, this expression calculates its factorial using the math.factorial() function from the math module.
- [math.factorial(x) for x in numbers]: This is the list comprehension itself. It iterates through the numbers in the numbers list, calculates the factorial of each number, and includes these factorials in the new list.
- print(numbers): This line of code prints the original numbers list to the console.
- print(factorials): This line of code prints the factorials list to the console.
Source Code
import math
numbers = [2, 3, 4, 5]
factorials = [math.factorial(x) for x in numbers]
print(numbers)
print(factorials)
Output
[2, 3, 4, 5]
[2, 6, 24, 120]