1

I am new to Python and i have been scribbling with lists. i want to only print out the positive numbers in my list,However only the first negative element gets removed, the second negative element remains as it is.

Here's my code:

def myfunc(mylist1) :
    print("List before sorting the elements : ", mylist1)
    mylist1.sort()
    print("List after sorting the elements : ", mylist1)
    for i in range(0,len(mylist1)) :
        if mylist1[i] <= 0  :
            del mylist1[i]

        else:
            break
    print("After Operations,Final list : ", mylist1)
    return
mylist = [67,78,54,-20,-23,44]
myfunc(mylist)

Output:

List before sorting the elements :  [67, 78, 54, -20, -23, 44]
List after sorting the elements :  [-23, -20, 44, 54, 67, 78]
After Operations,Final list :  [-20, 44, 54, 67, 78]
  • 1
    you're deleting from a list that you are iterating over which is causing weird results – gold_cy Jan 02 '20 at 12:57
  • Yes, as @aws_apprentice when you delete the first element (my_list[0]), the second element becomes the first element and in the second iteration the third element (currently second element) which is positive is checked and the loop breaks. – rashid Jan 02 '20 at 13:06
  • oh! that made it quiet clear. Thanks! – Prithvi Bose Jan 02 '20 at 13:14

1 Answers1

0

You can remove them with list comprehension. This is how you can define the function:

def myfunc(mylist1):
     return sorted([x for x in mylist1 if x > 0])
print(myfunc(mylist1))
Arn
  • 1,898
  • 12
  • 26