1

How do i achieve line 9 and 10 i.e the two for loops in python

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

newMatrix = []

for (i=0; i < len(matrix); i++):
    for (j=0; j < len(matrix[i]); j++):
        newMatrix[j][i] = matrix[i][j]
print newMatrix

PS: i know i can do [[row[i] for row in matrix] for i in range(4)] but how i do only using for loops

3
  • 4
    Matrix transformation can be done this way: zip(*matrix) Commented Sep 3, 2012 at 7:54
  • @Satoru.Logic: this should be an answer. Commented Sep 3, 2012 at 7:56
  • @thg435 Ok, now I've added an answer. Commented Sep 3, 2012 at 8:13

4 Answers 4

2

Use range (or xrange).

for i in range(len(matrix)):
  for j in range(len(matrix[i])):

FYI, assigning to newMatrix[i][j] will fail, because newMatrix is an empty list. You need to add a new empty list to newMatrix for every row and then append the new value to that list in every iteration.

Sign up to request clarification or add additional context in comments.

1 Comment

@WebDeveloper: I think I made that pretty clear in my answer. What part of it do you not understand? How have you tried to code it?
1

You can use the enumerate() function to loop over both the matrix values and give you indices:

newMatrix = [[0] * len(matrix) for _ in xrange(len(matrix[0]))]
for i, row in enumerate(matrix):
    for j, value in enumerate(row):
        newMatrix[j][i] = value

This outputs:

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

Because you are addressing rows and columns in the new matrix directly, you need to have initialized that new matrix with empty values first. The list comprehension on the first line of my example does this for you. It creates a new matrix that is (y, x) in size, given an input matrix of size (x, y).

Alternatively, you can avoid explicit looping altogether by (ab)using the zip function:

newMatrix = zip(*matrix)

which takes each row of matrix and groups each column in those rows into new rows.

In the generic case, python for constructs loop over sequences. The range() and xrange() functions can produce numerical sequences for you, these generate a number sequence in much the same way that a for loop in C or JavaScript would produce:

>>> for i in range(5):
>>>   print i,
0 1 2 3 4

but the construct is far more powerful than the C-style for construct. In most such loops your goal is to provide indices into some sequence, the python construct bypasses the indices and goes straight to the values in the sequence instead.

3 Comments

is'nt there a simple looping like in other languages. Y is it so complicated
@WebDeveloper: It's simpler looping; the complication lies in your new matrix needing initializing.
@WebDeveloper: Can you post a simpler example from any other language?
1

If I understand you correctly, what you want to do is a matrix transposition, which can be done this way:

 zip(*matrix)

Comments

1

Just to throw something else into the mix of answers, if you are doing any kind of matrix operations with Python, consider using numpy:

>>> import numpy
>>> matrix = numpy.matrix([
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12]
... ])

The transpose is pretty simple to do:

>>> matrix.transpose()
matrix([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.