I'm wondering if there is a way to "pop all" items from a list in Python?
It can be done in a few lines of code, but the operation seems so simple I just assume there has to be a better way than making a copy and emptying the original. I've googled quite a bit and searched here, but to no avail.
I realize that popping all items will just return a copy of the original list, but that is exactly why I want to do just that. I don't want to return the list, but rather all items contained therein, while at the same time clearing it.
class ListTest():
def __init__(self):
self._internal_list = range(0, 10)
def pop_all(self):
result, self._internal_list = self._internal_list[:], []
return result
# ... instead of:
# return self._internal_list.pop_all()
t = ListTest()
print "popped: ", t.pop_all()
print "popped: ", t.pop_all()
... which of course returns the expected:
popped: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
popped: []
This is exactly how it's done. The only substantial improvement that I can think of is to empty the list in-place:
def pop_all(l):
r, l[:] = l[:], []
return r
The difference between this and your version is the behavior on a list that is referenced from various places:
>>> a = [1, 2, 3]
>>> b = a
>>> pop_all(a)
[1, 2, 3]
>>> b
[]
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