0

So, basically I have a Queue (List of List of strings). Now, suppose I want to append 'okay' to the list at index 1, why is it getting appended for all the lists inside Queue? How do I append a value to a specific list only inside Queue?

Queue = []
temp = []
Queue.append(temp) # 12 - 8
Queue.append(temp)
Queue.append(temp)
Queue[1].append('okay')
print(Queue)
[['okay'], ['okay'], ['okay']]
Uddhav Bhagat
  • 63
  • 1
  • 2
  • 6

3 Answers3

1

Your Queue is a list of the exact same list

Queue.append(temp) does not create a new list and add it to Queue. Therefore when you change one element of Queue, you are actually changing them all.

Queue.append([]) should be used to populate the queue with separate, empty lists.

L.Grozinger
  • 2,280
  • 1
  • 11
  • 22
1

Because the three items in Queue are not three different empty lists: they're all temp. Thus temp, Queue[0], Queue[1] and Queue[2] are all the same object and modifying one of them has the result of modifying them all.

Try the following code instead:

Queue = []
Queue.append([])
Queue.append([])
Queue.append([])
Queue[1].append('okay')
print(Queue)
Stef
  • 13,242
  • 2
  • 17
  • 28
0

replace temp = [] with list()

Queue = [ ]
Queue.append(list()) # 12 - 8
Queue.append(list())
Queue.append(list())
Queue[1].append('okay')
print(Queue)
output: [[], ['okay'], []]
klv0000
  • 174
  • 10