Ayden
Ayden

Reputation: 37

Python list won't reset after going through this

I am running an empty list through the following function, the list being gp. The idea was to append a letter to the end of the list, then reset it once it reached a length of 9. However, it just stops appending new letters once gp reaches 9 characters. def upd(gp): gp.append(random.choice(string.letters)) if len(gp) > 9: gp = []

Upvotes: 1

Views: 635

Answers (1)

mhawke
mhawke

Reputation: 87084

Setting gp = [] does not mutate list gp, it simply rebinds the local variable gp to be an empty list. The external list (that was passed to the function in gp) is not affected by this rebinding.

What you need to do is to explicitly remove the items from the list. You can remove all items in one go like this:

def upd(gp):
    gp.append(random.choice(string.letters))
    if len(gp) > 9:
        gp[:] = []

Now this will mutate the list gp in place, effectively removing all its items. There are other ways to do it, e.g. del gp[:] will also work, and gp.clear() in Python 3 (thanks @PeterDeGlopper).

Upvotes: 4

Related Questions