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?
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
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.
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.
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
You are looking for:
del L[:]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With