-2

I want to increment index "i" by one and not add one to the value stored in "i". How do I do it?

I have tried "i+=1", "i=i+1", "i+1" - none of them works for me.

lst=[1,2,3]
for i in lst:
    print(i+1)

expected result:

2
3
index out of bound error

actual result:

2
3
4
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
infoweb
  • 3
  • 3

1 Answers1

0

Try below code, this will give you a range from 0 to 3(not inclusive) then iterate over my_list with the i.

my_list = [1,2,3]
for i in range(0,len(my_list)):
  print(my_list[i+1])

As a result you will be getting the expected result as

2
3
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: list index out of range

list index out of range is equivalent to java index out of bound error

Sunder R
  • 1,074
  • 1
  • 7
  • 21