Tuple of distinct prime factors of numbers in a list in Python


This Python code calculates and creates a tuple called prime_factors, which contains the prime factors of each number in 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.
  • prime_factors = tuple(factor for num in numbers for factor in range(2, num+1) if num % factor == 0 and all(factor % divisor != 0 for divisor in range(2, factor))): This line of code initializes a variable named prime_factors and assigns it a tuple created using a nested generator expression.
    • for num in numbers: This outer part of the code sets up a loop that iterates through each number num in the numbers list.
    • for factor in range(2, num+1): This inner part of the code sets up a nested loop that iterates through each number factor from 2 up to num (inclusive).
    • if num % factor == 0: Within the nested loop, it checks if num is divisible by factor by evaluating num % factor == 0.
    • all(factor % divisor != 0 for divisor in range(2, factor)) : Inside the condition, it uses all() to check if factor is a prime number. It does this by iterating through all numbers from 2 to factor - 1 (inclusive) and checking if factor is not divisible by any of them (i.e., factor % divisor != 0 for all divisor in that range).
    • factor: If all the conditions are met (i.e., num is divisible by factor and factor is a prime number), factor is included in the generator expression.
    • tuple(...): This surrounds the nested generator expression and converts the generated prime factors into a tuple.
  • print(numbers): This line of code prints the original numbers list to the console.
  • print(prime_factors): This line of code prints the prime_factors tuple (which contains the prime factors of the numbers) to the console.

Source Code

numbers = [10, 15, 20, 25]
prime_factors = tuple(factor for num in numbers for factor in range(2, num+1) if num % factor == 0 and all(factor % divisor != 0 for divisor in range(2, factor)))
print(numbers)
print(prime_factors)

Output

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

Example Programs