Question 9 of 16intermediate🔧 ApplyLong Answer4 marks

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.

Correct Answer

To solve this problem, we first read the number of elements n and create an empty list to store the input integers. Using a for loop, we read n integers from the user and append them to this list using the append() method.

Next, we initialize two empty lists to store the positive and negative numbers separately. We iterate through the original list and use conditional statements to check each element. If a number is greater than 0, it is appended to the positive list; if it is less than 0, it is appended to the negative list.

python n = int(input("Enter the number of elements: ")) original_list = [] for i in range(n): num = int(input("Enter element: ")) original_list.append(num)

positive_list = [] negative_list = []

for num in original_list: if num > 0: positive_list.append(num) elif num < 0: negative_list.append(num)

print("Original List:", original_list) print("Positive List:", positive_list) print("Negative List:", negative_list)

The program concludes by printing the original list along with the two newly created lists containing positive and negative numbers respectively.

Exercise: Programming Problems | Q: 2 | (Page 17)
For More Understanding

Explanation

The answer utilizes the concept of list creation and traversal as discussed in the NCERT textbook. It demonstrates how to create empty lists and use the append() function to populate them dynamically. The logic separates elements based on the condition (greater than or less than zero), which is a standard programming construct taught in the chapter on lists.

Solution Steps

  1. Step 1: Accept the number of elements 'n' from the user.

  2. Step 2: Create an empty list and use a loop to read 'n' integers, appending each to the list.

  3. Step 3: Create two empty lists for positive and negative numbers.

  4. Step 4: Iterate through the original list; if an element is > 0, append to positive list; if < 0, append to negative list.

  5. Step 5: Print the original list, the positive list, and the negative list.