Create a set of even numbers from 1 to 20


This Python code generates a set named evens containing even numbers in the range from 2 to 20 (inclusive). Here's how the code works:

  • evens = {x for x in range(2, 21, 2)}: This line uses a set comprehension to create the evens set. It iterates through numbers in the range from 2 to 20 (inclusive) with a step size of 2. This range includes all even numbers in that range.
  • The set comprehension {...} collects these even numbers and forms a set with distinct elements. Since sets do not allow duplicate values, only distinct even numbers are included in the set.
  • print(evens): This line prints the evens set to the console.

Source Code

evens = {x for x in range(2, 21, 2)}
print(evens)

Output

{2, 4, 6, 8, 10, 12, 14, 16, 18, 20}

Example Programs