views:

375

answers:

2
+5  Q: 

Clearing a list

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?

+26  A: 

You are looking for:

del L[:]
Thomas Wouters
Similarly, you can also do L[:] = []
Moe
+4  A: 

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.

Dana
He may be holding a reference to the list in another part of the program that would need to know that the list is empty.
Jason Baker
Maybe, but that's not what he asked. He was worried instead about losing a pointer to that particular location in memory, which is a dubious concept in Python anyhow.
Dana
He later clarified it in a comment.
ΤΖΩΤΖΙΟΥ