B_Furtado B_Furtado - 5 months ago 24
Python Question

Having difficulties to delete class instances from a list in python

I have seen a similar question OOP python - removing class instance from a list, but the solution is not working for me.

I made a full class test. And the result is not passing the test.

I'm using python 3.4.4

import random


A simple class

class J():
def __init__(self):
self.jota = 0

def up_j(self):
self.jota = random.choice([2, 0])

def get_j(self):
return self.jota

def __str__(self):
return str(self.jota)


A list in which I can append instances of the class

a = []


Appending class instances

for i in range(20):
a.append(J())


Changing it up a bit

for e in a:
e.up_j()


Here is the FUNCTION I want to get right



def x(a):
for i, o in enumerate(a):
if o.get_j() == 0:
del a[i]
return a


Applying the function

a = x(a)


Testing! Notice that all numbers in the result should be zero.
But that is not the case

for each in a:
print(each)


Results!

2
2
0
0
...

Answer

You are removing values from the list while iterating. This almost never works. Instead of deleting values out of the list while iterating, create a new list and append the values you care about (i.e. you wouldn't delete):

def x(a):
    ret = []
    for i, o in enumerate(a):
        if o.get_j() != 0:
           ret.append(o)
    return ret
Comments