tags:

views:

52

answers:

1

Hello all. I have a simple question. If I have a for loop in python as follows:

for name in nameList:

How do I know what the index is for the element name? I know I can some something like:

i = 0
for name in nameList:
    i= i + 1
    if name == "something":
        nameList[i] = "something else"

I just feel there should be a more readable way of doing this...

+7  A: 

Use the built in function enumerate.

for index, name in enumerate(nameList):
    ...
Manoj Govindan
Thanks, this is what I wanted
Richard
+1 They should include this in every tutorial.
delnan
This is clearly demonstrated in the python documentation
Falmarri