0

I know this is a basic question but here it's weird.

I have no idea why this is giving the error. plz help me with this. Thanks in advance

arr = [11,22,33,44,55,66,77]
brr = [1,2,3,4,55]
res_arr = arr

for i in range(len(arr)):
    if arr[i] in brr:
        res_arr.remove(arr[i])

Gives me the error List index out of range.

Any clues

EDIT :

This helped me solve the error.

res_arr = list(arr)

nnnnn
  • 79
  • 2
  • 9
  • `res_arr = arr` doesn't copy the list. Hence you're removing the items while iterating on the same list => composite duplicate – Jean-François Fabre Mar 27 '18 at 13:13
  • You are removing items from `res_arr` which has the same length as `arr`. As you are removing the items, the list is getting shorter and shorter, hence the error. Suppose you have 2 lists of 6 elements. You will then have indexes from 0 to 5. If you happen to delete an item from the 2nd list, it will be one element short compared to the original one. – IMCoins Mar 27 '18 at 13:16
  • There are 2 ways on countering this : * Instead of duplicating the list, and removing the elements. Just create a new one with the elements you wish. * Duplicate the list, and instead of removing the items from start to end, remove them from end to start, so you won't have the problem of out of bound range. – IMCoins Mar 27 '18 at 13:16
  • @Jean-FrançoisFabre is right that you should not remove from a list you are iterating over, however the error in this case is because `remove(item)` does not remove an item with value `item`, but the element at index `item` – Jesse Bakker Mar 27 '18 at 13:17
  • Thanks for the info jesse Bakker – nnnnn Mar 27 '18 at 13:24

1 Answers1

2

Use list comprehension . It is not a good idea to remove an element while iterating over it. And res_arr = arr does not do what you think. You need to look at how to copy objects in python

Ex:

arr = [11,22,33,44,55,66,77]
brr = [1,2,3,4,55]
print([i for i in arr if i not in brr])

Output:

[11, 22, 33, 44, 66, 77]

You can use the copy module to copy objects in python.

Ex:

import copy
res_arr = copy.deepcopy(arr)
Rakesh
  • 81,458
  • 17
  • 76
  • 113