Search code examples
pythonfor-loopindexingindices

Indices manipulation in Python


a = [3, 4, 5, 6, 7, 8]

for j in range(1, len(a)): #assigns as index the number given   
    print(j)    #1 2 3 4 5 Iterates from number given on 1st argument to length of "a"
    key = a[j]
    print(key)  #4 5 6 7 8 got index of j given 1, here starts at second number
    i = j - 1
    print(i)    #0 1 2 3 4 because of j - 1
    a[i+1] = a[i]
    print(i)    #0 1 2 3 4
    print(a[i]) #3 3 3 3 3 WHY?
    i = i - 1
    print(i)   #-1 0 1 2 3 because of i - 1
    a[i+1] = key
    print(key)  #4 5 6 7 8 [-1+1=0] WHY starts from 4?

My question really is, why manipulating the a[i+' '] messes up with the list? In here it's as a[i+1], but if I write a[i+3] it messes with all the numbers, why does that happen? how come they are linked?


Solution

  • I'll address this comment:

    print(a[i]) #3 3 3 3 3 WHY?
    

    You're basically copying the first element into the second, then the third, and so on. To see this, try running this code:

    a = [3, 4, 5, 6, 7, 8]
    for j in range(1, len(a)):
        i = j - 1
        a[i+1] = a[i]
        print(a)
    

    This yields:

    [3, 3, 5, 6, 7, 8]
    [3, 3, 3, 6, 7, 8]
    [3, 3, 3, 3, 7, 8]
    [3, 3, 3, 3, 3, 8]
    [3, 3, 3, 3, 3, 3]
    

    For this comment:

    print(key)  #4 5 6 7 8 [-1+1=0] WHY starts from 4?
    

    Note that in each iteration of the for loop, you are temporarily storing a[j] into a local variable called key. After you modify the list by making various assignments, the key variable will still contain a[j] by the end of the loop; it hasn't been modified! So it makes sense that printing the key later on will give you the same results as when you printed the key earlier.