That's pants!

05 Apr, 2017

Lee writes:

I'm not fully understanding the HugeHairyPants program on pages 72-73 of Python For Kids. I initially thought that the loop would produce "huge huge hairy hairy pants pants," reasoning that the program would assign the first value to i, then the identical value to j, and continue the loop. So why is the variable j assigned all of the values? My thought was that the program commands i to be the first variable ('huge'), then stops there because the variable j is introduced next. Since there is no other variables after j, it then gets assigned every variable. Is this correct? (It doesn't sound right to me, though.)

So let's break the code down a bit more then. Here's the list...

hugehairypants = ['huge', 'hairy', 'pants']

...and then the first two lines of the loop code:

for i in hugehairypants:
    print(i)

If we run this code right now we get:

huge
hairy
pants

Each time the value in i is (effectively) replaced with the next value in the list (it's actually not quite as simple as that, but it can be easier to think of it that way when you start programming).

It's important to remember that every time we loop here, we're executing all the statements in the block of code - that's the indented part. And that's why if we look at the original example...

for i in hugehairypants:
    print(i)
    for j in hugehairypants:
        print(j)

...it first executes print(i), then it executes the second for-loop - that's looping over the hugehairypants list again, calling print(j) three times, then back to print(i) again, and so on. If we just look at the print statements Python is executing in these two loops, this is what it looks like:

print(i) # first for-loop - the value in i is now 'huge'
print(j) # second for-loop - the value in j is now 'huge'
print(j) # second for-loop - the value in j is now 'hairy'
print(j) # second for-loop - the value in j is now 'pants'
print(i) # first for-loop - the value in i is now 'hairy'
print(j) # second for-loop - the value in j is now 'huge'
print(j) # second for-loop - the value in j is now 'hairy'
print(j) # second for-loop - the value in j is now 'pants'
print(i) # first for-loop - the value in i is now 'pants'
print(j) # second for-loop - the value in j is now 'huge'
print(j) # second for-loop - the value in j is now 'hairy'
print(j) # second for-loop - the value in j is now 'pants'

If you need something more visual, I suggest drawing two rectangles on a piece of paper with 3 cells. Write the 3 values from the list in the cells (obviously it's not really two lists, but easier this way). Get two small coins; the first coin marks the value in i, the second coin marks the value in j. Work through the code as though you were running it yourself - move each coin to show how the value changes as we loop:

Visual guide