简体   繁体   中英

Index out of range error when running a for loop to get values between list items

I am trying to append to an empty list the values in between two list items (1st & 2nd, 3rd & 4th etc. ) I'm running the below code in Jupyter notebook and I see the correct values that I am looking for, but with the index out of range error. When try to append to a list, I get the same error, but without seeing the output at all. I have also tried for x in range(0,len(head_list)): but I get the same error.

Code

head_list = [11,13,35,37,67,72]
final = [] 
x=0 
i=0 
for x in head_list:
    print(list(range(head_list[i]+1,head_list[i+1],1)))
    x=0
    i=i+2
# desired result: 
[12,36,68,69,70,71] 

Explanation

You get an IndexError because you try to access the index len(head_list) in the last iteration of your loop.

Code example

head_list = [11,13,35,37,67,72]
final = [] 

# iterate over the list length taking 2 steps at a time
for i in range(0, len(head_list)-1, 2):
    # concatenate the lists
    final = final + list(range(head_list[i]+1, head_list[i+1]))

print(final)

Output

[12, 36, 68, 69, 70, 71]

在此处输入图像描述

This will work.

for range need to bee -1 len of list

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