Could be an indentation issue. But we can’t tell b/c the code isn’t formatted. Plus, there’s no code that informs me that you’ve called the function w/an argument.
def purify1(lista):
even = lista
for i in range(len(lista)):
if lista[i] % 2 != 0:
del(even[i])
return even
def purify2(lista):
odd = []
even = []
for i in range(len(lista)):
if lista[i] % 2 != 0:
odd.append(lista[i])
else:
even.append(lista[i])
return even
L = [1,2,3,4,5,6]
print purify2(L)
print purify1(L)
It’s the del operator. It somehoes messes the code up. It’s in the first code. In the second one it works just fine.
The reason it doesn’t work correctly (or as expected) is because it is mutating the list (as in shortening) it is iterating. even is not a true copy, only a duplicate reference to the same list.
Bottom line, deleting members of a list causes everything to the right to move one index to the left to take up the void and maintain a contiguous index. When i is incremented it subsequently points to the next position, in effect skipping the one it should be pointing to.
Aside
To make an independent shallow copy of a list, there are two ways (three actually) to do this:
listb = lista[:]
listb = lista.copy()
listb = [x for x in lista]
Changes made to listb will not be mirrored in lista.
Now let’s consider one approach to mutating a list directly while iterating.
la = [1, 2, 3, 4, 5]
lb = la[:]
for x in lb:
if x % 2 == 0:
la.remove(x)
print la
lst1 = [1, 7, 12, 3, 44, 52]
blah = [v for i, v in enumerate(lst1) if i % 2 != 0]
print(blah)
[7, 3, 52]
#not sure why lists are now greyed out like comments when formatting the code.
Ok, thank you I get it now. I had no idea that when I changed even I also changed lista. It’s this about shallow copy and deep copy, I have to read more.