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.
Uttarakhand UbseTextbookSubjective· 3mImportance★★★★★est
67% · 20/30 Questions
✓ Free question
Read n integers into one list, then make a single pass: numbers >= 0 go to a positives
list, numbers < 0 go to a negatives list (append() on whichever branch matches).
Finally print all three lists.
The idea
This is a classic partition problem: one input list, two output lists, one if/else deciding
where each element belongs. We never modify the original list — we only copy elements out of it.
Program
# Split a list of integers into positives and negatives
n = int(input("How many integers? "))
numbers = []
for i in range(n):
numbers.append(int(input("Enter integer " + str(i + 1) + ": ")))
positives = []
negatives = []
for num in numbers:
if num >= 0:
positives.append(num)
else:
negatives.append(num)
print("Original list :", numbers)
print("Positive list :", positives)
print("Negative list :", negatives)
Sample run
How many integers? 6
Enter integer 1: 5
Enter integer 2: -3
Enter integer 3: 0
Enter integer 4: -12
Enter integer 5: 8
Enter integer 6: -1
Original list : [5, -3, 0, -12, 8, -1]
Positive list : [5, 0, 8]
Negative list : [-3, -12, -1]
Key lines explained:
- The first loop builds the input list with
append()— the standard read-n-values pattern. if num >= 0sends zero and positive numbers topositives; only strictly negative values go tonegatives. (If your teacher treats 0 as neither, change the test tonum > 0and add anelif num < 0branch — state your convention in the answer.)- Both output lists preserve the original order because we scan left to right.
✓Final answer
One pass with if num >= 0: positives.append(num) else: negatives.append(num);
for input [5, -3, 0, -12, 8, -1] it prints positives [5, 0, 8] and negatives [-3, -12, -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.