2

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

4
  • 2
    What do you mean by for clx[:] in clx and for x[:] in x? Commented Sep 10, 2015 at 10:32
  • same thing as in x[:] in x in earlier function. What I want it to mean is: For every element in list clx delete first element in this list until it's empty. Commented Sep 10, 2015 at 10:33
  • you might be have to try for c in clx[:]: Commented Sep 10, 2015 at 10:36
  • while clx also works. I'm curious, where does the for x[:] in x come from? It does look like it works on the string list, but I haven't seen it before. Commented Sep 10, 2015 at 10:38

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for help. It's even faster than previous anwer
0

Please try this to remove element from list

def remove_class_from_list():
    global clx
    for c in clx[:]:
        clx.remove(c)

1 Comment

This is a really inefficient (O(n^2)) and unpythonic method to do ctx = [].
0

Or you can add these 2 methods to your class:

def __iter__(self):
    return self

def next(self):
    if getattr(self, 'done', None):
        raise StopIteration
    self.done = True
    return 5

But I suggest that you learn python properly from some online tutorials on python.org

1 Comment

Primarily to motivate the user to learn about iterables and iterators. The exception raised and the accompanying error message could have made him curious.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.