Generate a list of numbers that are perfect squares from 1 to 100


This Python code creates a list called perfect_squares using a list comprehension to find and store perfect square numbers between 1 and 100. Here's how the code works:

  • perfect_squares = [x for x in range(1, 101) if int(x**0.5)**2 == x] : This line of code initializes a variable named perfect_squares 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 int(x**0.5)**2 == x: This is a condition that checks whether the current value of x is a perfect square. To determine if x is a perfect square, it calculates the square root of x using x**0.5, rounds it down to the nearest integer using int(), squares the result, and compares it to the original x. If they are equal, it means x is a perfect square.
    • [x for x in range(1, 101) if int(x**0.5)**2 == x]: This is the list comprehension itself. It iterates through the numbers in the specified range (1 to 100) and, for each number that is a perfect square, includes it in the new list.
  • print(perfect_squares): This line of code prints the perfect_squares list to the console.

Source Code

perfect_squares = [x for x in range(1, 101) if int(x**0.5)**2 == x]
print(perfect_squares)

Output

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Example Programs