Filtering out negative numbers from a set


This Python code uses a set comprehension to filter the positive numbers from a given set and creates a new set named positive_numbers. Here's how the code works:

  • import random: This line imports the random module, although it is not used in the code.
  • numbers = {1, -2, 3, -4, 5}: This line initializes a set named numbers with a collection of integers, including both positive and negative numbers.
  • positive_numbers = {x for x in numbers if x >= 0}: This line creates a new set named positive_numbers using a set comprehension.
    • for x in numbers: This part of the code iterates through each element in the numbers set.
    • if x >= 0: It checks whether each element is greater than or equal to zero, which filters out the positive numbers and zero from the numbers set.
  • print(numbers): This line prints the original numbers set to the console.
  • print(positive_numbers): This line prints the positive_numbers set (which contains only the positive numbers and zero) to the console.

Source Code

import random
 
numbers = {1, -2, 3, -4, 5}
positive_numbers = {x for x in numbers if x >= 0}
print(numbers)
print(positive_numbers)

Output

{1, 3, 5, -4, -2}
{1, 3, 5}

Example Programs