1

I've been trying to learn about lists and loops but i can't quite get around this 'project', my code is:

lista=[[0,1,2,3],[10,11,12,13]]
transp=[]
w=[]
for x in lista[::-1]:
    transp.append(w)
    for y in x:
        w.append(y)
   
print(transp)

it just prints

[[10, 11, 12, 13, 0, 1, 2, 3], [10, 11, 12, 13, 0, 1, 2, 3]]

and I can't understand why!

Appreciate your help

juju89
  • 554
  • 2
  • 5
  • 18
  • You can try and using debugging, or simply print the various variables within the loop. – skibee Oct 28 '20 at 20:55
  • [PythonTutor](http://pythontutor.com/visualize.html#code=lista%3D%5B%5B0,1,2,3%5D,%5B10,11,12,13%5D%5D%0Atransp%3D%5B%5D%0Aw%3D%5B%5D%0Afor%20x%20in%20lista%5B%3A%3A-1%5D%3A%0A%20%20%20%20transp.append%28w%29%0A%20%20%20%20for%20y%20in%20x%3A%0A%20%20%20%20%20%20%20%20w.append%28y%29%0A%20%20%20%0Aprint%28transp%29&cumulative=false&curInstr=15&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false) may help you understand why you have these two identical lists. – Mr. T Oct 28 '20 at 23:16

1 Answers1

0

You could just create the sublist if it does not exist or otherwise append to the appropriate one:

a = [[0, 1, 2, 3], [10, 11, 12, 13]]

transposed = []
for row in a:
  for idx, val in enumerate(row):
    if len(transposed) > idx:
      transposed[idx].append(val)
    else:
      transposed.append([val])

print(transposed)

Output:

[[0, 10], [1, 11], [2, 12], [3, 13]]
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40