Search code examples
pythonfor-loopnested-loops

Need help understanding Python Nested For Loop


I'm having trouble understanding the 2nd for loop in the code below:

di = [4,5,6]
for i in range(len(di)):
    total = di[i]
    for j in range(i+1,len(di)):
        total += di[j]
        curr_di = total / ((j-i+1)**2)

I can't visualize what happens in for j in range(i+1,len(di)):, in particular the i+1 portion confuses me. how does the i in the first loop affect the 2nd loop, if any?


Solution

  • The first loop is simply looping over the indices available in list di. For each entry in that loop, the second loop then examines the remaining portions of di.

    So, on the first iteration, we're examining the value 4. The second loop will then walk the list starting at that position, and running to the end (it will examine items 5 and 6).

    On the second iteration, we'll examine entry 5, then walk the remainder of the list in the second loop (in this case 6). Make sense?

    As a commenter pointed out, print statements are your friend. Here's an example with some print statements to show how i and j change:

    di = [4,5,6,7]
    for i in range(len(di)):
      print(f"i: {i}")
      total = di[i]
      for j in range(i+1, len(di)):
        print(f" - j: {j}")
        total += di[j]
        curr_di = total / ((j-i+1)**2)
    

    Output:

    i: 0
     - j: 1
     - j: 2
     - j: 3
    i: 1
     - j: 2
     - j: 3
    i: 2
     - j: 3
    i: 3