Create a set of numbers that are powers of 2 from 1 to 10


This Python code uses a set comprehension to create a set named powers_of_2 that contains the powers of 2 for x ranging from 1 to 10. Here's how the code works:

  • {2**x for x in range(1, 11)}: This set comprehension creates a set by iterating through the values of x from 1 to 10 (inclusive). For each value of x, it calculates the corresponding power of 2, 2**x, and includes it in the powers_of_2 set.
  • print(powers_of_2): This line of code prints the powers_of_2 set to the console.

Source Code

powers_of_2 = {2**x for x in range(1, 11)}
print(powers_of_2)

Output

{32, 64, 2, 128, 4, 256, 512, 1024, 8, 16}

Example Programs