for statement on empty iterable

Paul Rubin http
Wed Aug 22 02:17:38 EDT 2007


james_027 <cai.haibin at gmail.com> writes:
> Yes i am new to python :). I am sorry I should be clarify myself ...
> for example
> 
> l = ['j', 'a', 'm', 'e', 's']
> 
> for i in l
>  # i want to know the nth number of times it has loop thru or
> something like counter?

Oh I see.  You have to combine a couple of concepts but for this
example you'd say:

   name = 'james'     # 'l' looks too much like the digit 1
   for i,c in enumerate(name):
      print i, c
   print i

enumerate(name) generates the sequence 

   (0,'j'), (1,'a'), (2,'m'), (3,'e'), (4,'s')

and the above loop splits those tuples into two indexes i and c.

You should probably read the tutorial and work through the examples.
If you get something wrong with this basic stuff, your computer won't
explode or anything like that, so try stuff out.  Be more careful when
you start using library routines that can delete files ;).



More information about the Python-list mailing list