Create a list of numbers that are divisible by both 3 and 5 from 1 to 100


This Python code creates a list called divisible_by_3_and_5 using a list comprehension to find and store the numbers between 1 and 100 that are divisible by both 3 and 5. Here's how the code works:

  • divisible_by_3_and_5 = [x for x in range(1, 101) if x % 3 == 0 and x % 5 == 0]: This line of code initializes a variable named divisible_by_3_and_5 and assigns it the result of a list comprehension.
    • for x in range(1, 101): This part sets up a loop that iterates through numbers from 1 to 100 (inclusive). The range(1, 101) function generates a sequence of numbers starting from 1 and ending at 100.
    • if x % 3 == 0 and x % 5 == 0: This is a condition that checks whether the current value of x is divisible by both 3 and 5. The % operator calculates the remainder when x is divided by 3 and 5. If the remainder is 0 for both divisions, it means x is divisible by both 3 and 5.
    • [x for x in range(1, 101) if x % 3 == 0 and x % 5 == 0] : This is the list comprehension itself. It iterates through the numbers in the specified range (1 to 100) and, for each number that is divisible by both 3 and 5, includes it in the new list.
  • print(divisible_by_3_and_5): This line of code prints the divisible_by_3_and_5 list to the console.

Source Code

divisible_by_3_and_5 = [x for x in range(1, 101) if x % 3 == 0 and x % 5 == 0]
print(divisible_by_3_and_5)

Output

[15, 30, 45, 60, 75, 90]

Example Programs