matrix manipulation - why is a normal loop producing different results?

Viewed 34

My question is related to this question. I was trying to model the list comprehension provided by @shuttle87 in his/her answer to the question to a regular old-fashioned loop. Here is what my code snippet looks like:

matrix = [[2,0,2],[0,2,0],[2,0,2]]
sqd = []
for i in matrix:
    for e in i:
        sqd.append(e*e)
print(sqd)

My problem is that my code returns a list i.e., [4, 0, 4, 0, 4, 0, 4, 0, 4] instead of a matrix i.e., [[4, 0, 4], [0, 4, 0], [4, 0, 4]]. What can i be possibly doing wrong?

disclaimer: I am aware there are wonderful python libraries that can do this for e.g., numpy. I like understanding things through intuition and thus this question...so forgive my naivety.

3 Answers

You have a single list sqd that you are appending scalar values to, so it will always just be a 1-dimensional list. If you want a list of lists (i.e. 2-dimensional matrix), you need to append lists to sqd, not scalar values:

matrix = [[2,0,2],[0,2,0],[2,0,2]]
sqd = []
for i in matrix:
    row = []  # create a new list for each row
    for e in i:
        row.append(e*e)  # append scalar to the row list
    sqd.append(row)  # append row to matrix list
print(sqd)

Because you append numbers to sqd inside the inner for e in i loop. Instead, you need to append those numbers to a temp list, then append that list to sqd.

matrix = [[2,0,2],[0,2,0],[2,0,2]]
sqd = []
for i in matrix:
    row = []
    for e in i:
        row.append(e*e)
    sqd.append(row)
print(sqd)

Or, as a list-comprehension:

matrix = [[2,0,2],[0,2,0],[2,0,2]]
sqd = [[e * e for e in row] for row in matrix]
print(sqd)

You have two for loops here. Your outer loop is going through the Columns of the matrix.

Your inner loop is going through the rows.

Your inner loop runs through the entire loop before going down to your next column.

Now that you understand that flow, you need to see that your list "sqd" has only one operation it is performing. That operation of append will happen for every loop of the inner loop. Each loop you are growing that list by adding the latest operation.

To create the matrix you wish to see, you are going to want some more work between your inner and outer loop. I would recommend making a new list for every iteration of your outer loop. This new list will be appended by the inner loop, and once the inner loop completes, you can add this new temp list to "sqd".

Related