1

when adding an element to the history list it changes the rest by the element that I add

inputt="^<<<"
cordenadas=[0,0]
historial=[]
for i in inputt:
    if i == "^":
        cordenadas[0]+=1
    elif i== "v":
        cordenadas[0]-=1
    elif i== "<":
        cordenadas[1]-=1
    elif i== ">":
        cordenadas[1]+=1
    historial.append(cordenadas)
    print(historial)

this is the output

[[1, 0]]
[[1, -1], [1, -1]]
[[1, -2], [1, -2], [1, -2]]
[[1, -3], [1, -3], [1, -3], [1, -3]]
  • Do you want to maintain a list of moves made for each symbol or an aggregated list of moves made overall? – navneethc Apr 15 '21 at 21:47

3 Answers3

1

It happens due to the mutability of lists in Python.

  1. cordenandas will always point to the same item - unless you create a new list.
  2. It will append the same list every time you use .append.

Try moving cordenandas = [0, 0] into the for loop, and see what happens. Compare the behavior of the two programs using Python Tutor to get a better understanding of how Python references work.

Yam Mesicka
  • 6,243
  • 7
  • 45
  • 64
0
input = "^<<<"
historial = []
for i in input:
    cordenadas = [0, 0]
    if i == "^":
        cordenadas[0] += 1
    elif i == "v":
        cordenadas[0] -= 1
    elif i == "<":
        cordenadas[1] -= 1
    elif i == ">":
        cordenadas[1] += 1
    historial.append(cordenadas)
print(historial)
Anmol Parida
  • 672
  • 5
  • 16
0
inputt="^<<<"
cordenadas = [0,0]

historial=[]

for i in inputt:
    # declare a new list which contans 'cordenadas' values
    coord = [cordenadas[0],cordenadas[-1]]
    if i == "^":
        coord[0]+=1
    elif i== "v":
        coord[0]-=1
    elif i== "<":
        coord[1]-=1
    elif i== ">":
        coord[1]+=1
    # save the changes in the original list
    cordenadas = coord
    historial.append(coord)
    print(historial)
larou2si
  • 16
  • 1