Generate a list of numbers that are powers of 2 from 1 to 10


This Python code generates a list called powers_of_2 using a list comprehension to calculate the powers of 2 from 2^1 to 2^10. Here's how the code works:

  • powers_of_2 = [2**x for x in range(1, 11)]: This line of code initializes a variable named powers_of_2 and assigns it the result of a list comprehension.
    • for x in range(1, 11): This part sets up a loop that iterates through numbers from 1 to 10 (inclusive). It generates values for x.
    • 2**x: For each value of x, this expression calculates 2 raised to the power of x, which is equivalent to 2^x.
    • [2**x for x in range(1, 11)]: This is the list comprehension itself. It iterates through the values of x in the specified range (1 to 10) and calculates 2^x for each value, including the results in the new list.
  • print(powers_of_2): This line of code prints the powers_of_2 list to the console.

Source Code

powers_of_2 = [2**x for x in range(1, 11)]
print(powers_of_2)

Output

[2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]

Example Programs