Question

can we do using nested loop

Posted December 10, 2021 122 views
PythonDevelopment

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.

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
Submit an Answer
2 answers

Hi @ritikroushan2504,

It is possible, yes.

Here is a quick example showing how you use a list and see if it’s elements are negative or positive numbers. Once you know you just need to add them to another list and later on display them:

for number in ListOfPositiveAndNegative:
    if number < 0:
        ...

So what do we want to do? If they are positive add them to one list, if they are negative add them to another.

for number in ListOfPositiveAndNegative:
    if number < 0:
        PositiveList.append(number)
    else:
        NegativeList.append(number)

at the end it will look something similar to this:

ListOfPositiveAndNegative = [1,-2,3]                                                                                    NegativeList = []                                                                                                       PositiveList = []                                                                                                       for number in ListOfPositiveAndNegative:                                                                                    
    if number < 0:                                                                                                              
        NegativeList.append(number)                                                                                         
    else:                                                                                                                       
        PositiveList.append(number)                                                                                     print("Elements of the List:\n")                                                                                        print(NegativeList)