Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly remove elements from array in loop using Python

I tried to remove only one element from an array and print remaining ones in a loop:

arr = [1,2,3,4,5]
for i in arr:
    a = arr
    a.remove(i)
    print a

So I am expecting it to print this:

[2, 3, 4, 5]
[1, 3, 4, 5]
[1, 2, 3, 5]
[1, 2, 3, 4]

Why am I gettting the following results instead:

[2, 3, 4, 5]
[2, 4, 5]
[2, 4]
like image 414
sprogissd Avatar asked Jul 30 '26 13:07

sprogissd


1 Answers

This is a classic problem of deep vs shallow copy. Python copies the array by reference. So, any changes to the new variable (a in your case) will be reflected in the main array (arr). Removing element from a also remove elements from arr. You need to use following for creating a copy.

 a = arr[:] 

This will not remove any elements from arr.

like image 177
raks Avatar answered Aug 01 '26 02:08

raks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!