Python Loop: List Index Out of Range

前端 未结 4 1024
情话喂你
情话喂你 2020-11-28 15:10

Given the following list

a = [0, 1, 2, 3]

I\'d like to create a new list b, which consists of elements for which the current a

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 15:43

    When you call for i in a:, you are getting the actual elements, not the indexes. When we reach the last element, that is 3, b.append(a[i+1]-a[i]) looks for a[4], doesn't find one and then fails. Instead, try iterating over the indexes while stopping just short of the last one, like

    for i in range(0, len(a)-1): Do something

    Your current code won't work yet for the do something part though ;)

提交回复
热议问题