[Tutor] Re: modifying list of strings during iteration (without index)?
Jeff Kowalczyk
jtk@yahoo.com
Wed Jan 1 20:06:12 2003
"Bob Gailer" wrote:
> To replace in site:
> for i in range(len(li)):
> li[i] = li[i].strip()
[jtk] Ah, hence the enumerate function due in 2.3... Thanks.
PEP 279: The enumerate() Built-in Function
A new built-in function, enumerate(), will make certain loops a bit clearer.
enumerate(thing), where thing is either an iterator or a sequence, returns a iterator that
will return (0, thing[0]), (1, thing[1]), (2, thing[2]), and so forth.
Fairly often you'll see code to change every element of a list that looks like this:
for i in range(len(L)):
item = L[i]
# ... compute some result based on item ...
L[i] = result
This can be rewritten using enumerate() as:
for i, item in enumerate(L):
# ... compute some result based on item ...
L[i] = result