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.
Asked
Active
Viewed 546 times
0
-
`i` is the element not the index... and post code & errors as text, not images. – Jean-François Fabre May 05 '17 at 09:32
-
4What happened Wednesday? – tiwo May 05 '17 at 09:34
-
Possible duplicate of [Looping Through List Returns Negative Index](http://stackoverflow.com/questions/43525168/looping-through-list-returns-negative-index) – Jean-François Fabre May 05 '17 at 09:37
-
When you do `for i in list` then i becomes an element of the list not an index, so you cannot do `list[i]` – May 05 '17 at 09:38
-
@tiwo Brain fog? – Rolf of Saxony May 05 '17 at 11:39
2 Answers
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