Hey, i just need help with this

Hey i just need help with this bit of code.

def purify(lista):
for i in range(len(lista)):
if lista[i] % 2 != 0:
del lista[i]
return lista

Im just wondering why it doesn’t work. It’s purpose is to take a list and return the list without the odd elements.

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.

Please use the “</>” button to format your code.

1 Like

Okay, i think I’ve found what doesn’t make sense

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. :slight_smile:

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

[1, 3, 5]

3 Likes

you could also use a list comprehension,

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.
2 Likes

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.

After the opening triple tick type python

```python

2 Likes

I am using the button, “</>” to insert formatted code and never had an issue with it. I will use your suggestion next time. :slight_smile:

1 Like