Search code examples
pythonnested-lists

Hello, I'm just learning. Can someone help me to understand how this code knows where to put the X. I'm just not seeing it. Thanks


row1 = ["⬜️","️⬜️","️⬜️"]
row2 = ["⬜️","⬜️","️⬜️"]
row3 = ["⬜️️","⬜️️","⬜️️"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure? ")

horz = int(position[0])
vert = int(position[1])

### This is what I don't understand ###
selected = map[vert - 1]
selected[horz - 1] = "X"
###

print(f"{row1}\n{row2}\n{row3}")

I used 23 as the input: I understand some of this I just don't understand how it knows what row.

There is the list map Then the nested lists row1 row2 and row3 inside the list map. The input is stored in vert and horz.

That's where my understanding ends. The rows are stacked so how does it know where the X goes in row3 in the 2nd position.


Solution

  • I've changed the code slightly to make the cells indicate the number to access it and make the added print statements easier to follow:

    row1 = ['11','21','31']
    row2 = ['12','22','32']
    row3 = ['13','23','33']
    map = [row1, row2, row3]
    print(f'{row1}\n{row2}\n{row3}')
    position = input('Where do you want to put the treasure? ')
    
    horz = int(position[0])
    print(f'{horz=}')
    vert = int(position[1])
    print(f'{vert=}')
    
    ### This is what I don't understand ###
    selected = map[vert - 1]
    print(f'{selected=}')
    selected[horz - 1] = 'XX'
    print(f'{selected=}')
    ###
    
    print(f'{row1}\n{row2}\n{row3}')
    

    Output (with comments):

    ['11', '21', '31']
    ['12', '22', '32']
    ['13', '23', '33']
    Where do you want to put the treasure? 23
    horz=2                                       # horz selects the column
    vert=3                                       # vert selects the row
    selected=['13', '23', '33']                  # selected refers to row3 (map[2])
    selected=['13', 'X', '33']                   # change selected (map[2][1])
    ['11', '21', '31']
    ['12', '22', '32']
    ['13', 'XX', '33']
    

    In Python, variables are names of objects. selected = map[vert - 1] where vert = 3 makes selected becomes another name for the item in map[2] which is the same item referred to by the name row3.

    selected[horz - 1] = 'XX' where horz = 2 changes row3[1] to XX. Since that same item is in in the map, the change is reflected there as well.