0

I've composed a code to transpose a 2d array in Python but it doesn't work correctly and all rows of the transposed array are similar to last column of the original array. Can anybody help me to find out the problem?

a = [[1, 3, 2],
    [6, 7, 3],
    [2, 0, 1],
    [9, 0, 4]]

b = [[*range(len(a))]] * len(a[0])


for i in range(len(a)):
    for j in range(len(a[0])):
        b[j][i] = a[i][j]
print(a)
print(b)
  • It doesn't work because `b` contains **the same list** three times, so changing an element of that list changes the entire "row". See the second linked duplicate for details. The first linked duplicate explains how to do the transposition simply and directly. *In general*, algorithms that try to "allocate space" and then modify a new data structure are tricky; it's usually better to write code that directly creates the desired modified result - either through functional tools like `zip` and list comprehensions, or by `.append`ing to an empty list instead of assigning to indexes sequentially. – Karl Knechtel Jul 02 '22 at 19:41
  • Also: welcome to Stack Overflow. In the future, [please try](https://meta.stackoverflow.com/questions/261592) to look for existing questions before asking. – Karl Knechtel Jul 02 '22 at 19:45
  • Thank you so much, but I find a way to create b: b = [] for i in range(len(a[0])): b += [[0]] for j in range(len(b)): for t in range(len(a)-1): b[j] += [0] – Alimohamad Jul 02 '22 at 20:19

0 Answers0