Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the index of a list in a loop

Tags:

python

loops

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...

like image 849
Richard Avatar asked Oct 26 '25 12:10

Richard


1 Answers

Use the built in function enumerate.

for index, name in enumerate(nameList):
    ...
like image 151
Manoj Govindan Avatar answered Oct 29 '25 02:10

Manoj Govindan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!