Python is going to be hard

Ian Kelly ian.g.kelly at gmail.com
Wed Sep 3 21:11:51 CEST 2014


On Wed, Sep 3, 2014 at 12:49 PM, Seymore4Head
<Seymore4Head at hotmail.invalid> wrote:
> On Wed, 03 Sep 2014 14:10:42 -0400, Seymore4Head
> <Seymore4Head at Hotmail.invalid> wrote:
>
>>import math
>>import random
>>import sys
>>b=[]
>>steve = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>for x in steve:
>>    print (steve[x])
>>
>>Traceback (most recent call last):
>>  File "C:\Functions\blank.py", line 7, in <module>
>>    print (steve[x])
>>IndexError: list index out of range
>
> Ok, I understand now that x is actually the first item in the list.
> What I want is a loop that goes from 1 to the total number of items in
> the list steve.

If you want the indexes also, you can do this:

for i, x in enumerate(steve):
    print(i, x)

If you really want just the indexes and not the values, then you can do this:

for i in range(len(steve)):
    print(i)

Most of the time though you will not need the indexes, and it will be
simpler just to work with the values by looping directly over the
list.



More information about the Python-list mailing list