Skip to content
Advertisement

nested list content does not preserve when appending to a main list

I’m working on a basic program allows me to navigate in a two dimensions grid (for now 3X3), using a function specified with the initial point and all the steps moved on each axis, returning the end point. I want to raise an error if a specific point has been already visited, and I’m trying to do it by logging all previous points. This is my code:

matrix = [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]

def position(inital_point,*steps):
    end_point = inital_point
    point_logs = []
    point_logs += end_point
    for step in steps:
        end_point[0] += step[0]; end_point[1] += step[1]
        point_logs += end_point
    print(point_logs)

My problem is, I want to reference each point with a nested list inside the main list, but the code above is giving me this result:

position([1,1],[1,1],[1,1])
>>>[1, 1, 2, 2, 3, 3]

When I try to convert it to a nested list, I get:

matrix = [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]

def position(inital_point,*steps):
    end_point = inital_point
    point_logs = []
    point_logs += [end_point]
    for step in steps:
        end_point[0] += step[0]; end_point[1] += step[1]
        point_logs += [end_point]
    print(point_logs)
        
position([1,1],[1,1],[1,1])
>>> [[3, 3], [3, 3], [3, 3]]

Instead of simply [[1, 1],[2, 2],[3, 3]], please help!

Advertisement

Answer

This approach basically takes the last appended points from point_logs and adds the new coordinates to it after which it is also appended.

def position(inital_point,*steps):
    end_point = inital_point
    point_logs = []
    point_logs.append(end_point)
    for step in steps:
        x, y = point_logs[-1]
        point_logs.append([x+step[0], y+step[1]])
    print(point_logs)

Output

[[1, 1], [2, 2], [3, 3]]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement