CameraIcon
CameraIcon
SearchIcon
MyQuestionIcon
MyQuestionIcon
150
You visited us 150 times! Enjoying our articles? Unlock Full Access!
Question

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.

Open in App
Solution

Program:
#Defining empty list
list1 = list()

#Getting the input of number of elements to be added in the list
inp = int(input("How many elements do you want to add in the list? (Element can be both positive and negative) "))

#Taking the input of elements to be added
for i in range(inp):
a = int(input("Enter the elements: "))
list1.append(a)

#Printing the list
print("The list with all the elements: ",list1)

#Defining list2 and list3 to store positive and negative elements of the list
list2 = list()
list3 = list()

#Looping through list to segregate positive and negative numbers
for j in range(inp):
if list1[j] < 0:
#Appending negative elements to list3
list3.append(list1[j])
else:
#Appending positive elements to list2
list2.append(list1[j])


print("The list with positive elements: ",list2)
print("The list with negative elements: ",list3)


OUTPUT:
How many elements do you want to add in the list? (Element can be both positive and negative) 5
Enter the elements: -1
Enter the elements: -2
Enter the elements: -3
Enter the elements: 4
Enter the elements: 5
The list with all the elements: [-1, -2, -3, 4, 5]
The list with positive elements: [4, 5]
The list with negative elements: [-1, -2, -3]

flag
Suggest Corrections
thumbs-up
7
Join BYJU'S Learning Program
similar_icon
Related Videos
thumbnail
lock
Organisation of Data
MATHEMATICS
Watch in App
Join BYJU'S Learning Program
CrossIcon