1

I'm having trouble getting the output I want. I want to create a list and have the first element of a new list be that initial list. Then I want to modify the first list, and have the new modified version of that list be the second element of the new list. Right now, this outputs [[2,3,4,5,5],[2,3,4,5,5]]. How would I modify it so that the output is [[1,2,3,4,5], [2,3,4,5,5]]?

noChange = [1,2,3,4,5]
lotsOfLists = []

lotsOfLists += [noChange]

for i in range(4):
    noChange[i] += 1
lotsOfLists += [noChange] 

print(lotsOfLists) # current output: [[2, 3, 4, 5, 5], [2, 3, 4, 5, 5]]
# WANT: [[1,2,3,4,5], [2,3,4,5,5]]
k-156
  • 13
  • 2

3 Answers3

0

Whenever you use the line

lotsOfLists += [noChange] 

change it to

lotsOfLists += [noChange[:]] 

Adding the [:] will make a copy of the list and not change it later

Buzz
  • 1,877
  • 21
  • 25
0

Lists are mutable, that is causing the trouble. Use slices for copies.

noChange = [1,2,3,4,5]
lotsOfLists = []

lotsOfLists += [noChange[:]]

for i in range(4):
    noChange[i] += 1
lotsOfLists += [noChange[:]] 

print(lotsOfLists) #output [[1, 2, 3, 4, 5], [2, 3, 4, 5, 5]]
0

Lists are accessed by reference, so you need .copy() to create a new one.

noChange = [1,2,3,4,5]
lotsOfLists = []

lotsOfLists += [noChange.copy()]

for i in range(4):
    noChange[i] += 1
lotsOfLists += [noChange]

print(lotsOfLists) # output: [[1,2,3,4,5], [2,3,4,5,5]]

As others say, you can also use the slicing operator [:] to achieve the same result. IMHO, the semantics is different. With the slicing operator, you tell a reader that you want to slice something. With the copy() operation, you tell a reader, that you want to copy something.

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222