Home > Net >  Deleting and moving all negative numbers from one list to another list - Did not work?
Deleting and moving all negative numbers from one list to another list - Did not work?

Time:08-13

I'm trying to move the negative numbers from one array to another. The result I have misses certain elements, e.g. -12 and -14.

    arr=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]
    arr1=[]
    for i in arr:
            if i < 0:
                arr1.append(i)
                arr.remove(i)
    print (arr,arr1)

The result is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -12, -14] [-11, -13, -15]

Why -12 and -14 are not moved?

CodePudding user response:

When you remove an element in arr while looping, this change its content for the next round.
correct code is the following in two steps:

arr=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]
arr1=[]
for i in arr:
        print (i)
        if i < 0:
            arr1.append(i)
for i in arr1:
    arr.remove(i)
print (arr,arr1) 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [-11, -12, -13, -14, -15]

HTH

CodePudding user response:

The reason that you did not get your items removed is just because while looping and removing at the same time, the pointer index is just jumping off...

It's best to do 2-loops, or you insist one loop then - doing from the backwards. It's because operation from the backward, the operation will NOT affect the indexing.

for x in arr[::-1]:
    if x < 0: 
        arr1.append(x)
        arr.remove(x)

    
>>> arr
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> arr1                        # if orig. order is not important 
[-15, -14, -13, -12, -11]

To understand what's happening in your original code: Run this::

for idx, x in enumerate(arr):
    if x < 0:
        print(idx, x)
        arr1.append(x)
        arr.remove(x)
        
print (arr,arr1)

  • Related