2

I'm trying a create a random blank matrix in python 3 without using numpy. The Code looks perfect but when I change a single cell's value (for example Square1[0]) it changes all the Square1[x] values.

#!/usr/bin/env python3

# Creating a random n*n blank matrix
#for example 6*6

#I'll just create coloumns
def one():

    square = []
    for x in range(6):
        square.append(None)

    Square = []
    for x in range(6):
        Square.append(square)

    return Square

#output is exactly what i want
print(one())

#but when i try to change a single value(cell),

a = one()

a[2][2] = "Error"

#it's bullshit
print(a)

What is wrong with me or my code?

1
  • 1
    Try this: pastebin.com/DKsnEpNJ - What do you expect as output? Then execute it. Did you guess the right output. I'm pretty sure you didn't. Think about why the output is different. Commented Jul 29, 2014 at 18:37

2 Answers 2

1

Square is a list of six references, all pointing to the same square list. Modifying any of these square references will affect all rows. You can confirm this by looking at the id values of the rows:

a = one()
print id(a[0])
print id(a[1])

result:

37725768
37725768

Instead of making a single square and appending it six times, make six squares and append each one once.

def one():
    Square = []
    for y in range(6):
        square = []
        for x in range(6):
            square.append(None)
        Square.append(square)
    return Square

Now the rows will all refer to different lists.

a = one()
print id(a[0])
print id(a[1])
#result:
#37827976
#37829192

I also suggest changing square's name, since it's pretty confusing to have two variable names that only differ in capitalization.

def make_matrix():
    matrix = []
    for y in range(6):
        row = []
        for x in range(6):
            row.append(None)
        matrix.append(row)
    return matrix
Sign up to request clarification or add additional context in comments.

Comments

1

You code fails because you append 6 references to the same array. See Kevin's answer for a more detailed explanation.

A more "pythonic" way to create your array:

array = [[None]*n for x in range(n)]

This uses a list comprehension.

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.