-2

I have a function (Python 3):

import queue

q = queue.Queue()

q.put(1)
q.put(2)
q.put(3)

def printqueue(u):
    while not u.empty():
        print(u.get())

printqueue(q)

print(q.empty())

Why is q empty at the end while I operated on u? Is there a way to fix this?

ruohola
  • 21,987
  • 6
  • 62
  • 97
big papa
  • 47
  • 2
  • 4
  • You did not operate on a copy. Repeat any tutorial on passing a mutable sequence object to a function. – Prune Feb 20 '21 at 17:57

1 Answers1

2

Because you do not operate on a copy of it, but instead the exact same object.

You can easily check this with the built-in id function:

import queue

q = queue.Queue()

def printqueue(u):
    print(id(u))

print(id(q))
printqueue(q)

Output:

140230517913872
140230517913872
ruohola
  • 21,987
  • 6
  • 62
  • 97