2

I think there is some major programming concept I am missing.

I get the current position of a wire and want to append it to a list.

The current position is always correct, and appends correctly. But when I start appending the next position (which is also correct) it changes my first value I already appended.

wire = ['R8','U5','L5','D3']

# Current position
wire_pos = [0,0]
# A list of all past positions
wire_path = []

for dir in wire:
    if 'R' in dir:
        # The value with the directon 'R' stripped out
        wire_pos[0] += int(dir[1:])
        # Append this current position to the path list
        wire_path.append(wire_pos)
    elif 'L' in dir:
        wire_pos[0] -= int(dir[1:])
        wire_path.append(wire_pos)
    elif 'U' in dir:
        wire_pos[1] += int(dir[1:])
        wire_path.append(wire_pos)
    elif 'D' in dir:
        wire_pos[1] -= int(dir[1:])
        wire_path.append(wire_pos)
print(wire_path)

current output = [[3, 2], [3, 2], [3, 2], [3, 2]] expected output= [[8, 0], [8, 5], [3, 5], [3, 2]]

Extend works, but my values are no longer in list form. I also tried dictionary by yielded the same result as lists.

Matt H.
  • 21
  • 1
  • 6
    You keep appending *the same list* to your list, creating a list with 4 references to the same list, so of course they all have the same value – juanpa.arrivillaga Dec 08 '19 at 22:17

0 Answers0