Skip to content
Programming Problems · Q2

Q.Write a program to read a list of n integers (positive as well as negative). Create two new lists, one having all positive numbers and the other having all negative numbers from the given list. Print all three lists.

Puducherry TnboardTextbookSubjective· 5mImportance★★★★★est
54% · 14/26 Questions
✓ Free question

Build the main list while reading input, then (or simultaneously) partition it: each number goes to the positives list if its sign test passes, otherwise to the negatives list — one selection inside one loop.

The idea. This combines the two core list skills: building lists with append() and classifying elements with a condition. A single loop can do both jobs at once — read, store, and route each number by its sign.

Program:

n = int(input("How many integers? "))

numbers = []
positives = []
negatives = []

for i in range(n):
    num = int(input("Enter integer " + str(i + 1) + ": "))
    numbers.append(num)
    if num >= 0:
        positives.append(num)
    else:
        negatives.append(num)

print("Original list:", numbers)
print("Positive numbers:", positives)
print("Negative numbers:", negatives)

Key lines: the three lists start empty; numbers.append(num) preserves the full input; the if num >= 0 test routes the value (0, if entered, is grouped with the non-negatives — state your convention; the problem promises positive and negative values).

Expected output (sample run with n = 6 and inputs 12, -4, 7, -9, 3, -1):

How many integers? 6
Enter integer 1: 12
Enter integer 2: -4
Enter integer 3: 7
Enter integer 4: -9
Enter integer 5: 3
Enter integer 6: -1
Original list: [12, -4, 7, -9, 3, -1]
Positive numbers: [12, 7, 3]
Negative numbers: [-4, -9, -1]

Partition trace:

numnum >= 0?goes to
12Yespositives
-4Nonegatives
7Yespositives
-9Nonegatives
3Yespositives
-1Nonegatives

Both output lists preserve the original order of their members — a natural property of the single left-to-right pass. Time complexity O(n).

Tip

The compact alternative once the list exists: positives = [x for x in numbers if x >= 0] and negatives = [x for x in numbers if x < 0] — two list comprehensions expressing the same partition.

✓Final answer

Read n integers into numbers, appending each to positives (num >= 0) or negatives (num < 0), then print all three lists; the sample input [12, -4, 7, -9, 3, -1] yields Positive: [12, 7, 3] and Negative: [-4, -9, -1].

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.