0

I have a problem where I want to have a nested for loop concatenate a string. For some reason I'm not getting the correct output. Can someone give me some advice? This should be simple.

newRow = []
matrix = []
for i in range(0,3):
    for j in range(0,5):
        newRow.append(j)
    matrix.append(newRow)
print matrix

python test.py

[[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4], 
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4], 
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]]

I want it to print...

[[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]
1
  • 5
    That's not a string, that's not concatenating, and your indentation is off. Commented Feb 19, 2012 at 2:59

5 Answers 5

5

You keep adding to the same newRow. If you want to get a clean row, you need to create an empty one on each iteration:

matrix = []                                      newRow = [] <- the same array
for i in range(0,3):                             matrix = []
    newRow = [] <- a new array                   for i in range(0,3):
    for j in range(0,5):         instead of          for j in range(0,5):
        newRow.append(j)                                 newRow.append(j)
    matrix.append(newRow)                            matrix.append(newRow)

There are, of course, more pythonic ways of achieving this, but I'm trying to point out what the problem with the code is.

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

Comments

3

You can make this if you want nested loop:

matrix = [ [  i for i in range(5)] for j in range(3)]
print matrix 
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

Comments

1
matrix = []
for i in range(0,3):
    matrix.append(list(range(0, 5)))

or even:

matrix = [list(range(0, 5)) for i in range(0, 3)]

Comments

1

You are close, its just a matter of properly scoping:

matrix = []
for i in range(0,3):
    newRow = []
    for j in range(0,5):
        newRow.append(j)
    matrix.append(newRow)
print matrix

Comments

0

Whatever you do,

DON'T DO THIS

DON'T DO THIS

DON'T DO THIS:

>>> x = [range(0,5)]*3
>>> x
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
>>> x[0][0] = 'LOL'
>>> x
[['LOL', 1, 2, 3, 4], ['LOL', 1, 2, 3, 4], ['LOL', 1, 2, 3, 4]]

use a list comprehension.

1 Comment

That gives you three references to the same row. If you set matrix[0][0], you're also effectively setting matrix[1][0].

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.