Tuple of positive and negative numbers from a list in Python


This Python code creates two tuples: positive and negative, which contain the positive and negative numbers from the numbers list, respectively. Here's how the code works:

  • numbers = [10, -5, 20, -15, 30]: This line initializes a variable named numbers and assigns it a list containing five numbers, some of which are positive, and some 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, it checks if it is greater than or equal to 0 (i.e., a non-negative number) using the condition x >= 0.
    • x: If a number is non-negative, it includes it in the generator expression.
    • tuple(...): This surrounds the generator expression and converts the generated non-negative numbers into a tuple.
  • negative = tuple(x for x in numbers if x < 0): This line of code initializes a variable named negative and assigns it a tuple created using a generator expression.
    • for x in numbers: Similar to the previous generator expression, this loop iterates through each number x in the numbers list.
    • if x < 0: For each number, it checks if it is less than 0 (i.e., a negative number) using the condition x < 0.
    • x: If a number is negative, it includes it in the generator expression.
    • tuple(...): This surrounds the generator expression and converts the generated 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.
  • print(negative): This line of code prints the negative tuple (which contains the negative numbers from the list) to the console.

Source Code

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

Output

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

Example Programs