[Tutor] walking a list

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 11 Dec 2001 23:44:20 -0800 (PST)

On Wed, 12 Dec 2001, Kirk Bailey wrote:

> Sokay, now try to walk it in a for loop:
> for i in members:
> 	print members[1]
> Gets this error:
> Traceback (most recent call last):
>   File "<pyshell#119>", line 2, in ?
>     print members[i]
> TypeError: sequence index must be integer

> ok, how do I get it to walk through a loop, performing a block of code
> for each item in the list?

In your loop above:

> for i in members:
> 	print members[1]

'i' isn't a number: it's one of the lines in your member's list.  Here's
an example with the interpreter that shows a little more about this:

>>> three_stooges = ['larry', 'curly', 'moe']
>>> for stooge in three_stooges:
...     print "nuk nuk", stooge
nuk nuk larry
nuk nuk curly
nuk nuk moe

So this works.

In a 'for' loop,

    for <index_variable> in <some_sequence>

the index_variable will go over the elements in some_sequence.

Hope this helps!