orhanodabasi
orhanodabasi

Reputation: 982

Create a Random Blank Matrix (2D array) in Python 3?

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?

Upvotes: 2

Views: 390

Answers (2)

Azar
Azar

Reputation: 1106

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.

Upvotes: 1

Kevin
Kevin

Reputation: 76194

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

Upvotes: 1

Related Questions