Python Forum
Query in list.clear (beginner)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Query in list.clear (beginner)
#1
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?
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to find difference between elements in a list? Using beginner Basics only. Anklebiter 8 4,256 Nov-19-2020, 07:43 PM
Last Post: Anklebiter
  Simple beginner query--Please help!Thanks Nienie 3 2,386 Jun-26-2020, 04:58 PM
Last Post: pyzyx3qwerty
  list and sort query arian29 2 2,166 Sep-18-2019, 06:19 PM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020