Generate a list of positive numbers from another list


This Python code takes a list of numbers, filters out the positive numbers, and stores them in a new list called positive_numbers. Here's how the code works:

  • numbers = [1, -2, 3, -4, 5, -6]: This line initializes a variable named numbers and assigns it a list containing six numbers, some of which are negative.
  • positive_numbers = [x for x in numbers if x > 0]: This line of code initializes a variable named positive_numbers and assigns it the result of a list comprehension.
    • for x in numbers: This part sets up a loop that iterates through each number x in the numbers list.
    • if x > 0: This condition checks whether the current number x is greater than 0. If x is positive, it proceeds to the next part.
    • [x for x in numbers if x > 0]: This is the list comprehension itself. It iterates through the numbers in the numbers list and, for each positive number, includes it in the new list.
  • print(numbers): This line of code prints the original numbers list to the console.
  • print(positive_numbers): This line of code prints the positive_numbers list to the console.

Source Code

numbers = [1, -2, 3, -4, 5, -6]
positive_numbers = [x for x in numbers if x > 0]
print(numbers)
print(positive_numbers)

Output

[1, -2, 3, -4, 5, -6]
[1, 3, 5]

Example Programs