简体   繁体   中英

What happens when we a negative value in python's for loop?

x = 10
l = [1]
for i in range(x):
    # Modified v
    print("Row", i + 1, l)
    newlist = []
    newlist.append(l[0])
    for i in range(len(l) - 1):
        newlist.append(l[i] + l[i+1])
    newlist.append(l[-1])
    l = newlist

I dont understand what happens when the index goes negative

When you give negative index, value at that index is returned. For list a=[1,2,3]

we can say

value 1 is at index 0
value 2 is at index 1
value 3 is at index 2

or

value 3 is at index -1
value 2 is at index -2
value 1 is at index -3

If you go outside this range of indexes which is in this case negative 3 to positive three, you will get

IndexError: list index out of range

For your code, second for block is never executed and hence you are not seeing index error.

x = 10
l = [1]
for i in range(x):
  print("Row", i + 1, l)

newlist = []

newlist.append(l[0])


# Length l is 0,so below code inside for is never executed as range is empty
for i in range(len(l) - 1):
    newlist.append(l[i] + l[i+1])
    newlist.append(l[-1])
    l = newlist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM