Hermes Morales
Hermes Morales

Reputation: 637

Functions for manipulating nested lists

1) If I do:

tablero = [[' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' 
'], [' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' '], [' 
', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ']]
def dibujar_cruz():
    x = 0
    a = "X"
    size = len(tablero)
    for row in tablero:
        tablero[x][x] = a  
        tablero[x][size-x-1]=a        
        x += 1      
    for l in tablero:
        print (" ".join(l))
dibujar_cruz()

I obtain:

an star of size 6

2) But if the function "dibujar_cruz()" takes the initial nested list from another function like this:

tablero =[]
def construir_tablero():
    size =int(input("Which is the size of the nested lists? "))
    col=[]
    for x in range (size):
        col .append(" ")
    for b in range(size):
        tablero.append(col)
    return (tablero)
print (construir_tablero())
def dibujar_cruz():
    x = 0
    size = len(tablero)
    for row in tablero:
        row [x]= "X"
        row[size-x-1]="X"
        x += 1    
    for l in tablero:
        print (" ".join(l))
dibujar_cruz()

I obtain:

Square obtained calling the two functions consecutively

When I expected to have the same star as in point 1).

3) If I define a third function that calls the two first ones:

def construir_cruz():
    construir_tablero()
    dibujar_cruz()
construir_cruz()

I expected to obtain the same star as in 1) but I obtain an Error:

... row[size-x-1]="X"

IndexError: list assignment index out of range

The results in 2) and 3) were unexpected for me. Why did I obtain them?

Upvotes: 2

Views: 71

Answers (2)

Hermes Morales
Hermes Morales

Reputation: 637

The problem in point 3) is that when repeating the function

construir_cruz() 

it already has a tablero in memory. Changing the position of the definition of tablero from:

tablero = []    
def construir_tablero():
    size =int(input("Which is the size of the nested lists? "))
    col=[]
    for x in range (size):
        col .append(" ")
    for b in range(size):
        tablero.append(col)
   return (tablero)

to

def construir_tablero():
    tablero =[]
    size =int(input("Which is the size of the nested lists? "))
    col=[]
    for x in range (size):
        col .append(" ")
    for b in range(size):
        tablero.append(col)
    return (tablero)

solves the problem, because it redefines tablero in each call.

Upvotes: 0

xhienne
xhienne

Reputation: 6134

As stressed by Ilja Everilä in comment, your array tablero contains X copies of the same array col, but this is a copy by reference, not by value. Therefore, each time you modify one of the columns in tablero, the change appears in every columns.

The solution is to copy col by value. Just change:

tablero.append(col)

to:

tablero.append(col[:])

Upvotes: 1

Related Questions