Search code examples
pythonclasspython-2.7python-3.xdel

Removing classes from list in Python


Why I can remove strings in list but not classes? Is it possible to do if there are classes in list? What is correct way to do this?

class Temp():
    def __init__(self, name, name2):
        self.n = name
        self.n2 = name2

cltemp1 = Temp("1", "2")
cltemp2 = Temp("3", "4")

x = ["1", "2"]
clx = [cltemp1, cltemp2]


def remove_string_from_class():
    global x

    for x[:] in x:
        del x[0]

remove_string_from_class()

print x


def remove_class_from_list():
    global clx

    for clx[:] in clx:
        del clx[0]

remove_class_from_list()

print clx

TypeError: can only assign an iterable


Solution

  • To remove every item from a list, simply use lst = []. If you need to mutate the list object without reassigning it, you can use lst[:] = [] instead.

    As for why your version doesn't work:

    You are iterating over the list in the wrong manner. Iteration should look like for var in lst. The fact that your function works on the string list is mostly accidental: it replaces x[:] with the first string, and then deletes that string. It won't work correctly with all values (e.g. x = ['11', '22']), and as you saw it gives an error when the list contains non-iterables.