Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:  []
like image 601
Micke Avatar asked Dec 15 '22 01:12

Micke


1 Answers

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
[]
like image 120
Fred Foo Avatar answered Jan 05 '23 00:01

Fred Foo