0

I defined a function that changes list (basically moves the last item to the start of list) and then i tried to make a 2d list with this fuction.

Here's some code:

prevRow = ["blue", "yellow", "red", "black", "white"]
def nextRow():
    prevRow.insert((0, prevRow.pop()))
    print(prevRow)
    return  prevRow
tablePreset = [["blue", "yellow", "red", "black", "white"], nextRow(), nextRow(), nextRow(), nextRow()]
print(tablePreset)
prevRow = ["blue", "yellow", "red", "black", "white"]
tablePreset = [["blue", "yellow", "red", "black", "white"]]
def nextRow():
    prevRow.insert((0, prevRow.pop()))
    print(prevRow)
    return  prevRow
for _ in range(4):
    tablePreset.append(nextRow())
print(tablePreset)

in both cases i got the

['white', 'blue', 'yellow', 'red', 'black']
['black', 'white', 'blue', 'yellow', 'red']
['red', 'black', 'white', 'blue', 'yellow']
['yellow', 'red', 'black', 'white', 'blue']
[['blue', 'yellow', 'red', 'black', 'white'], ['yellow', 'red', 'black', 'white', 'blue'], ['yellow', 'red', 'black', 'white', 'blue'], ['yellow', 'red', 'black', 'white', 'blue'], ['yellow', 'red', 'black', 'white', 'blue']]

I don't know why but even though i called function 4 times, every return in the list is the same as the last value (print inside the function is for debugging purposes).

I'll be very greatfull if someone helps me :)

1 Answers1

0

You need to make a copy of the list every time it's passed to the function nextRow (see code below). Some more information here (related topic).

prevRow = ["blue", "yellow", "red", "black", "white"]
tablePreset = [["blue", "yellow", "red", "black", "white"]]

def nextRow(prevRow):
    prevRow_copy = prevRow.copy()
    prevRow_copy.insert(0, prevRow_copy.pop())
    return prevRow_copy

for _ in range(4):
    prevRow = nextRow(prevRow)
    tablePreset.append(prevRow)
    
print(tablePreset)

# >> out:
# [['blue', 'yellow', 'red', 'black', 'white'],
#  ['white', 'blue', 'yellow', 'red', 'black'],
#  ['black', 'white', 'blue', 'yellow', 'red'],
#  ['red', 'black', 'white', 'blue', 'yellow'],
#  ['yellow', 'red', 'black', 'white', 'blue']]

Another small example illustrating the importance of the copy:

a = []
b = [1,2,3]

a.append(b)
b.pop()
a.append(b)
b.pop()
a.append(b)

print(a)

# >> out:
# [[1], [1], [1]]

a = []
b = [1,2,3]

a.append(b.copy())
b.pop()
a.append(b.copy())
b.pop()
a.append(b.copy())

print(a)

# >> out:
# [[1, 2, 3], [1, 2], [1]]
akensert
  • 284
  • 1
  • 2
  • 7