0

I'm a beginner in programming, and I'm trying to write code for transposing a matrix. When I run the below code, a logic error occurs:

def transpose(matrix):
   x=0
   trans=len(matrix[0])*[[]]
   for list in matrix:
       for element in list:
           trans[x].append(element)
           x+=1
       x=0
   return trans
transpose([[1,2,3], [4,5,6]])

Output: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]]

But when I replace line 3 with trans=[[ ],[ ],[ ]] the code works good! What's the difference between [[ ],[ ],[ ]] and 3*[[ ]]? Thanks

IanS
  • 15,771
  • 9
  • 60
  • 84
  • 2
    You should try to take as small parts of your code as possible, to understand it ... try: `a = 3*[[]]` `a[0].append(1)` `print a` -> you see? – Ilja Mar 13 '16 at 18:43
  • yes I got it and edit my code, It work good def transpose(matrix): x=0 lis=[] b=len(matrix[0]) while b!=0: lis.append([]) b-=1 for list in matrix: for element in list: lis[x].append(element) x+=1 x=0 return lis – mohammad hassan jafari Mar 13 '16 at 18:53

0 Answers0