Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing the value of a list index inside a Queue of Lists

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading