Tuple of Negative numbers from a list in Python


This Python code creates a tuple called negative, which contains all the negative 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.
  • 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: 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 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(negative): This line of code prints the negative tuple (which contains the negative numbers from the list) to the console.

Source Code

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

Output

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

Example Programs