Home > Blockchain >  Changing the value of a list index inside a Queue of Lists
Changing the value of a list index inside a Queue of Lists

Time:12-01

I am trying to create a Queue in Python with the following code

data = queue.Queue(maxsize=4)
lists = [None] * 3
for i in range(4):
    data.put(lists)

Which initiates a Queue of 4 Lists with three None elements in each list as seen below

> print(data.queue)
deque([[None, None, None], [None, None, None], [None, None, None], [None, None, None]])

Now, I want to edit the elements of the list in place to look like this:

deque([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])

And I attempt to do so with this code:

x = 0
for lst in data.queue:
    for elem in lst:
        elem = x
        x  = 1 
print(data.queue)

But it does not change the values of the list elements and still returns

deque([[None, None, None], [None, None, None], [None, None, None], [None, None, None]])

Is there any way to modify the contents of the Lists inside of a Queue object?

CodePudding user response:

First, if you put lists each time, you are referencing the same list. You need to do

data = queue.Queue(maxsize=4)
for _ in range(4):
    data.put([None] * 3)
    
data.queue

Next, use index to update values

x = 0
for lst in data.queue:
    for i in range(len(lst)):
        x  = 1
        lst[i] = x
         
print(data.queue)
# deque([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
  • Related