Tuple of positive numbers from a list in Python


This Python code creates a tuple called positive, which contains all the non-negative (i.e., positive or zero) numbers from the numbers list. Here's how the code works:

  • numbers = [-5, 10, -15, 20, -25]: This line initializes a variable named numbers and assigns it a list containing five numbers, some of which are negative.
  • positive = tuple(x for x in numbers if x >= 0): This line of code initializes a variable named positive and assigns it a tuple created using a generator expression.
    • for x in numbers: This part of the code sets up a loop that iterates through each number x in the numbers list.
    • if x >= 0: For each number in the list, it checks if x is greater than or equal to zero by evaluating x >= 0.
    • x: If the number is non-negative (positive or zero), it includes it in the generator expression.
    • tuple(...): This surrounds the generator expression and converts the generated non-negative numbers into a tuple.
  • print(numbers): This line of code prints the original numbers list to the console.
  • print(positive): This line of code prints the positive tuple (which contains the non-negative numbers from the list) to the console.

Source Code

numbers = [-5, 10, -15, 20, -25]
positive = tuple(x for x in numbers if x >= 0)
print(numbers)
print(positive)

Output

[-5, 10, -15, 20, -25]
(10, 20)

Example Programs