1

I'm trying to go through an array from any position l to the end, but once it reaches the last position instead of leaving the while cycle it shows me an error "list index out of range"

while l <= len(ordenado):
      ñ = ordenado[l]
      contador2 = contador2+ñ
      l = l+1

I've seen many answers about this theme but I haven't been able to apply it to my problem, also any help will be really appreciated.

2
  • 3
    You probably want to use l < len(ordenado) instead of <= Commented Mar 10, 2018 at 2:16
  • @bla He might not know it yet, but what he really wants is a for loop. Or just sum(). Commented Mar 10, 2018 at 4:08

2 Answers 2

3

python list are 0 indexed so you need to use.

while l < len(ordenado):

for your case for loop is more suitable.

mylist = ['a', 'b', 'c']

for i, item in enumerate(mylist):
    print(i, item) #where i will be 0,1,2 and item will be a,b,c
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a language which arrays/lists are not 0-indexed?
I think vba is.
2

Replace

while l <= len(ordenado):

With:

while l < len(ordenado):

The reason is that python list indices range from zero to len(ordenado) - 1.

Example

>>> mylist = ['a', 'b', 'c']
>>> mylist[0]
'a'
>>> mylist[len(mylist)-1]
'c'
>>> mylist[len(mylist)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

As you can see, mylist[len(mylist)-1] accesses the last element of the list. Any index larger than that will generate an IndexError.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.