Tuple of tuples with element and its factorial in Python


This Python code processes the numbers list and creates a tuple called factorial_tuples. Each element in this tuple is a pair containing a number from the list and its factorial computed using the math.factorial function. Here's how the code works:

  • import math: This line imports the math module, which provides mathematical functions, including the factorial function.
  • numbers = [1, 2, 3, 4, 5]: This line initializes a variable named numbers and assigns it a list containing five numbers.
  • factorial_tuples = tuple((x, math.factorial(x)) for x in numbers): This line initializes a variable named factorial_tuples and assigns it a tuple created using a generator expression.
  • print(numbers): This line of code prints the original numbers list to the console.
  • print(factorial_tuples): This line of code prints the factorial_tuples tuple (which contains pairs of numbers and their factorials) to the console.

Source Code

import math
numbers = [1, 2, 3, 4, 5]
factorial_tuples = tuple((x, math.factorial(x)) for x in numbers)
print(numbers)
print(factorial_tuples)

Output

[1, 2, 3, 4, 5]
((1, 1), (2, 2), (3, 6), (4, 24), (5, 120))

Example Programs