Python Forum
Query in list.clear (beginner) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Query in list.clear (beginner) (/thread-17945.html)



Query in list.clear (beginner) - Shaswat - Apr-30-2019

Hello Everyone,

I am new in Python programming and trying to transpose the matrix. So if the matrix is

matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12],]

the output will be

# Transpose output [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]].

Here is my code:

t=[]
k=[]

for x in range(0,4): #range(0,3) [y,x]
    for y in range(len(matrix)):
        t.append(matrix[y][x])
    k.append(t)
    #t.clear() #seems issue
    t=[]
print(k)
To clear the content of list t, initially I used t.clear() which causes the output becomes
Output:
[[], [], [], []]
Alternatively, I replace it with the t=[] and it works perfectly providing output
Output:
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
As per the Python documentation, t.clear() "remove all items from the list and equivalent to del a[:]".
If I already append the value of t in k before clearing the content of t, then print(k) should print the correct values instead blank. Why t.clear() causes printing null values inside the list?

Could you please explain what I missed?


RE: Query in list.clear (beginner) - ichabod801 - Apr-30-2019

Lists are mutable, which means they are passed around with pointers to the list, not the list itself. So after your first append of t to k, t and k[0] both point to the same list. So t.clear() also clears k[0]. On the other hand, t = [] assigns a new list to the label t. So now t points at the new list, and k[0] points at the old t.

Note that you shouldn't iterate over indexes, you should iterate over the lists themselves. So better code would be:

new_matrix = []
new_row = []
for row in matrix:
    for item in row:
        new_row.append(item)
    new_matrix.append(new_row)
    new_row = []
While this is probably a good answer to your homework assignment, note that new_matrix = list(zip(*matrix)) transposes a matrix all by itself. Note that the rows become tuples instead of lists, but there are ways to change that.