Iteration index
Paul Winkler
slinkp23 at yahoo.com
Thu May 31 15:52:32 EDT 2001
Marek Augustyn wrote:
>
> Hello!
>
> 1. Do I have to use additional variable when I want to know iteration index?
> Example:
>
> s = ('a', 'b', 'ala', 'a')
> i = 0 # additional variable
> for el in s:
> print i, el
> i += 1
Most people do use the extra variable, but I think it's safe to
say that
most python programmers use the built-in range() and len()
functions, like so:
s = ('a', 'b', 'ala', 'a')
for i in range(len(s)):
print i, s[i]
If len(s) is very large, you could use xrange() instead of
range().
I guess you could do it without the variable like this:
!! WARNING -- this only works if you use a list instead of a tuple
AND you know that the list contains no duplicate items!!
s = ['a', 'b', 'ala', 'a']
for el in s:
print s.index(el), el
But I wouldn't do that - too many assumptions about the input.
In the example given, it prints this:
0 a
1 b
2 ala
0 a
... not what you want.
>
> 2. Are there block comments in Python? (like /* */ in C)
Nope, but you can use doc strings with triple quotes:
"""
This string can be very long
and contain as much stuff
as you want.
"""
HTH,
--PW
More information about the Python-list
mailing list