0

Since Wednesday, for loop is not working correctly in Python(2.7) in (with windows 10). See screen shot. Its skipping the 1st and somestimes the 2nd element (index 0 and 1). A similar while loop works fine.

Screen shot of simple example. For loop skips index 0 and 1. While loop wrks fine

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
BethC
  • 11

2 Answers2

1

Okay, so if you are using for loop you should either go:

for i in my_list:
    print i

Or:

for i, element in enumerate(my_list):
    print my_list[i]

In both cases don't call your variable list as it is a reserved keyword for actual list.

zipa
  • 27,316
  • 6
  • 40
  • 58
0

You already have an answer but hopefully this might explain what is going on

>>> l =[1,2,3,4]
>>> l
[1, 2, 3, 4]
>>> for i in l:
...  print "value of i=",str(i), "value of l at index[i]", str(l[i])
... 
value of i= 1 value of l at index[i] 2
value of i= 2 value of l at index[i] 3
value of i= 3 value of l at index[i] 4
value of i= 4 value of l at index[i]
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: list index out of range

There is no value available at l[4] as the starting position is l[0] through to l[3]

Rolf of Saxony
  • 21,661
  • 5
  • 39
  • 60