-1

I wanted to make a function that rotates a 2-dimentional list in python like so:
input: [[0,1,2,3],[0,1,2,3]]

output: [[0,0],[1,1],[2,2],[3,3]]

I wanted to first create a list with placeholder None values so I could easily put in the values later. I came up with this code:

matrix = [[0,1,2,3],[0,1,2,3]]#debugging value, will be an argument of the function. 
output = []
row= []
for x in range(len(matrix)):
    row.append(None)
for x in range(len(matrix[0])):
    output.append(row)

So, this creates a nice starting point to now organise the data, but now something weird happens. If I now try to run something like output[0][0] = 5, the output variable suddenly has the following values: [[5, None], [5, None], [5, None], [5, None]], while this line should only affect the first list in the list. Even stranger, now the value of the temporary list row is [5, None]. The line should not affect this variable at all. Am I missing something, or is this a bug in Python? I tried this on Python 3.7.6 on windows and Python 3.8.2 on Linux. Can someone please help me with this?

Stefan
  • 13
  • 4
  • 2
    look at the [`zip`](https://docs.python.org/3.3/library/functions.html#zip) builtin function whicch does exactly what you want – Tryph Aug 27 '20 at 12:40

1 Answers1

1

You can use zip()

lst_input=[[0,1,2,3],[0,1,2,3]]

def rotate_list(lst_input):
    lst_output=[]
    for a,b in zip(lst_input[0],lst_input[1]):
        lst_output.append([a,b])
    return lst_output

print(rotate_list(lst_input))
#[[0, 0], [1, 1], [2, 2], [3, 3]]
Andreas
  • 8,694
  • 3
  • 14
  • 38
  • 1
    Or just use `list(zip(*lst_input))` (or `list(list(a) for a in zip(*lst_input))` if you are really set on a list of lists). – Heike Aug 27 '20 at 12:45