List of numbers with their divisors


This Python code creates a dictionary called divisors where each key-value pair represents a number from the numbers list and its divisors. 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.
  • divisors = {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 divisors and assigns it the result of a dictionary comprehension.
    • for num in numbers: This part sets up a loop that iterates through each number num in the numbers list.
    • range(1, num+1): This creates a range of numbers from 1 to num (inclusive). These are the potential divisors of num.
    • [x for x in range(1, num+1) if num % x == 0] : This list comprehension iterates through the numbers in the range and includes only those numbers that are divisors of num. It checks if num is divisible by x (i.e., num % x == 0).
    • {num: [x for x in range(1, num+1) if num % x == 0] for num in numbers}: This is the dictionary comprehension itself. It iterates through the numbers in the numbers list, calculates the divisors for each number, and stores them as key-value pairs in the divisors dictionary.
  • print(numbers): This line of code prints the original numbers list to the console.
  • print(divisors): This line of code prints the divisors dictionary (which contains the divisors of each number) to the console.

Source Code

numbers = [10, 15, 20, 25]
divisors = {num: [x for x in range(1, num+1) if num % x == 0] for num in numbers}
print(numbers)
print(divisors)

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