Tuple of factors of numbers in a list in Python


This Python code creates a tuple called factors, which contains pairs of numbers and their factors from the numbers list. Here's how the code works:

  • numbers = [10, 15, 20, 25]: This line initializes a variable named numbers and assigns it a list containing four numbers.
  • factors = tuple((num, [x for x in range(1, num+1) if num % x == 0]) for num in numbers): This line of code initializes a variable named factors 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(factors): This line of code prints the factors tuple (which contains pairs of numbers and their factors) to the console.

Source Code

numbers = [10, 15, 20, 25]
factors = tuple((num, [x for x in range(1, num+1) if num % x == 0]) for num in numbers)
print(numbers)
print(factors)

Output

[10, 15, 20, 25]
((10, [1, 2, 5, 10]), (15, [1, 3, 5, 15]), (20, [1, 2, 4, 5, 10, 20]), (25, [1, 5, 25]))

Example Programs