0

In this task I can only write the function and the rest of the code is given, so the original list l in the function should be changed without creating a new one. However, as I understood it when I already read through similar questions, this is not a good idea at all.

My try looked like this:

import random

def removeNegatives(listOfIntegers):
   for i in listOfIntegers:
        if i < 0:
            listOfIntegers.remove(i)
            
                 
#code can not be changed from here on!     

l = []

for i in range(0, random.randint(15,25)):
  l.append(random.randint(-15,15))

print ("Before:", l)
removeNegatives(l)
print ("After:", l)
Janys02
  • 31
  • 5

1 Answers1

-1

As you need to change the list in place, you can loop in reverse to avoid affecting the order while poping elements:

def removeNegatives(listOfIntegers):
    for pos in range(len(listOfIntegers), 0, -1):
        if listOfIntegers[pos-1] < 0:
            listOfIntegers.pop(pos-1)

example output:

Before: [15, 7, -1, 3, -6, -2, 10, -1, 4, 5, -10, -8, 9, 9, 13, -11, 1, -4, -9, -15, -8, 3, 1]
After: [15, 7, 3, 10, 4, 5, 9, 9, 13, 1, 3, 1]

NB. it is more efficient to change the list only once, you can use the following code to overwrite the full list with new (filtered) elements:

def removeNegatives(listOfIntegers):
    listOfIntegers[:] = filter(lambda i: i>0, listOfIntegers)
mozway
  • 194,879
  • 13
  • 39
  • 75
  • Repeated `pop`s are terrible performance-wise. Better build from scratch, `loi[:] = filter((0).__le__, loi)` – user2390182 Oct 24 '21 at 13:35
  • @user2390182 I tried to keep the original loop as slicing might be more confusing to beginners. But I'll add a note – mozway Oct 24 '21 at 13:38