Question

I find it annoying that I can't clear a list. In this example:

a = []
a.append(1)
a.append(2)

a = []

The second time I initialize a to a blank list, it creates a new instance of a list, which is in a different place in memory, so I can't use it to reference the first, not to mention it's inefficient.

The only way I can see of retaining the same pointer is doing something like the following:

for i in range(len(a)):
    a.pop()

This seems pretty long-winded though, is there a better way of solving this?

Was it helpful?

Solution

You are looking for:

del L[:]

OTHER TIPS

I'm not sure why you're worried about the fact that you're referencing a new, empty list in memory instead of the same "pointer".

Your other list is going to be collected sooner or later and one of the big perks about working in a high level, garbage-collected language is that you don't normally need to worry about stuff like this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top