Generate a list of tuples containing numbers and their signs


This Python code takes a list of numbers and creates a new list called num_signs using a list comprehension. The new list contains pairs of numbers and their associated sign ('positive' or 'negative') based on whether the number is greater than zero or not. Here's how the code works:

  • numbers = [-2, 3, -5, 7, -11]: This line initializes a variable named numbers and assigns it a list containing five numbers, some of which are negative.
  • num_signs = [(x, 'positive') if x > 0 else (x, 'negative') for x in numbers]: This line of code initializes a variable named num_signs 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.
    • (x, 'positive') if x > 0 else (x, 'negative'): For each number in the list, this expression checks if x is greater than 0. If x is greater than 0, it creates a tuple containing the number x and the string 'positive'. If x is not greater than 0 (i.e., it's zero or negative), it creates a tuple containing the number x and the string 'negative'.
    • [(x, 'positive') if x > 0 else (x, 'negative') for x in numbers] : This is the list comprehension itself. It iterates through the numbers in the numbers list, determines the sign of each number, and pairs each number with its associated sign, including these pairs (tuples) in the new list.
  • print(numbers): This line of code prints the original numbers list to the console.
  • print(num_signs): This line of code prints the num_signs list to the console.

Source Code

numbers = [-2, 3, -5, 7, -11]
num_signs = [(x, 'positive') if x > 0 else (x, 'negative') for x in numbers]
print(numbers)
print(num_signs)

Output

[-2, 3, -5, 7, -11]
[(-2, 'negative'), (3, 'positive'), (-5, 'negative'), (7, 'positive'), (-11, 'negative')]

Example Programs