Search code examples
pythonpython-2.7list-comprehension

Popping all items from Python list


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:  []

Solution

  • In fact, why not just

    def pop_all(self):
        result, self._internal_list = self._internal_list, []
        return result
    

    ... if you are reassigning self._internal_list anyway, why not just return the old one instead of copying it?