Strange error in For in Python

Asked

Viewed 50 times

-1

Hello, my friend.

I’m making a very stupid mistake that I can’t even understand why it’s wrong.

a = [1, 4, 5]
b = []
for i in range(0,len(a)):
  c = a[i+1]
  b.append(c) 

The mistake is

IndexError: list index out of range

how so the copier does not understand that i = 0, I want a[1]??

Thank you for your attention

2 answers

1

Because you use +1 inside the brackets, when i do for arrives at the last position, it tries to access a non-existent position. Either you range between -1 and Len(a)-1 or remove +1
If you want to skip the first position, just make the range start from 1 (you also need to remove the +1)

1


Explanation of how it is currently:

a = [1, 4, 5]
b = []
for i in range(0,len(a)):
    c = a[i+1] # primeiro 1, depois 2 e depois 3, você não tem a posição 3 no seu list a, você tem as posições 0, 1 e 2
    b.append(c)

If you were to transfer the values, a better code would be:

a = [1, 4, 5]
b = []
for i in a:
    c = a[i]
    b.append(c)

Here are examples with repeating structures with range and other ways http://curso.grupysanca.com.br/pt/latest/repeticao.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.