Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 772
Dan Avatar asked Oct 03 '08 11:10

Dan


People also ask

How to clear a list (remove all of the items)?

How to clear a List (remove all of the Items)? -1 Empy a dictionary and a list in Python -4 Python trying to clear and reuse list 35 Different ways of deleting lists 2 Clear a list in a function each time it's run 2 Deleting a list in python, getsizeof() non zero? 1

What is Python list clear () method?

Python List clear () Method 1 Definition and Usage. The clear () method removes all the elements from a list. 2 Syntax 3 Parameter Values. Thank You For Helping Us! Your message has been sent to W3Schools. W3Schools is optimized for learning and training.

What is the purpose of the clear method in a list?

The purpose is just to empty all value from the list to reuse the list. Is there any side effect with using method2. Should I favor one method to the next. I also found a similar question, Using the "clear" method vs.

How to clear a list in a_Listan?

To clear it just make the following: a_list = list(empt_list) this will make a_listan empty list just like the empt_list. Share Improve this answer


2 Answers

You are looking for:

del L[:]
like image 124
Thomas Wouters Avatar answered Oct 05 '22 15:10

Thomas Wouters


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.

like image 32
Dana Avatar answered Oct 05 '22 16:10

Dana