0

Running the following code causes some strange behavior in python 2.7 and 3.5:

class Test():
    def __init__(self):
        self.arr = [1,2,3,4,5,6]
    def worker(self):
        for x in self.arr:
            print (self.arr.pop(0))

b = Test()
b.worker()

Will cause the following output

>>> b.worker()
1
2
3
>>> b.worker()
4
5
>>> b.worker()
6

While the following code sample works as expected, printing the whole array in one go:

class Test():
    def __init__(self):
        self.arr = [1,2,3,4,5,6]
    def worker(self):
        for x in range(len(self.arr)):
            print (self.arr.pop(0))

b = Test()
b.worker()

>>> b.worker()
1
2
3
4
5
6

What is going on here, why doesn't the first code sample print and reduce (pop) the whole array when the worker() is called?

Eplox
  • 143
  • 7

0 Answers0