Python Forum

Full Version: Nested loop indexing
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Basically, I'm just trying to understand the logic for the nested loop inputs and outputs. The first nested loops seems to append either a # or a space for 20 values 60 times. So, I understand that I'm inputting either a # or space 20 times per row? What confuses me is the second nested for loop. The WIDTH and HEIGHT are inverted. You start off X with width and then y with height. I don't understand this. In my second nested loop I tried to make the range of the outer loop WIDTH and the inner HEIGHT, but I get an indexing error but I don't understand why? I'm just using the same indexing I used in the previous? How come I have to invert the WIDTH AND HEIGHT for the second nested loop?

WIDTH = 60
HEIGHT = 20

nextCells = []
for x in range(WIDTH):
    column = []
    for y in range(HEIGHT):
        if random.randint(0,1):
            column.append('#')
        else:
            column.append(' ')
    nextCells.append(column)

while True:
    print('\n\n\n\n\n')
    currentCells = copy.deepcopy(nextCells)

    for y in range(HEIGHT):
        for x in range(WIDTH):
            print(currentCells[x][y],end='')
        print()
To match the first for loops the second loops should be
for x in range(WIDTH):
    for y in range(HEIGHT):
not
for y in range(HEIGHT):
    for x in range(WIDTH):
Also, note you would probably want the inner loop to be the WIDTH and the outer loop to be the HEIGHT
I see, although not quite. After reviewing how these lists interacted with these nested loops I'm more confused. I'm coming from C++ and I know that arrays are used for stuff like this but it seems different. I don't see why accessing a list would require an x and y since it doesn't seem to be a multidimensional list. Then again I have no idea.
(Aug-04-2020, 06:59 AM)Morte Wrote: [ -> ]since it doesn't seem to be a multidimensional list.

Assuming "it" is currentCells, why do you think that? It's a copy of nextCells and nextCells appears to be a multidimensional list (really just a list of lists).
Now I see what I was doing wrong. I looked over how deepcopy was working and treated it like an array instead of a list so I need to review more. Thank you for bringing the list of list up. Now wonder I was indexing incorrectly.