Search code examples
pythonenumerate

Understanding pythons enumerate


I started to teach myself some c++ before moving to python and I am used to writing loops such as

   for( int i = 0; i < 20; i++ )
   {
       cout << "value of i: " << i << endl;
   }

moving to python I frequently find myself using something like this.

i = 0
while i < len(myList):
   if myList[i] == something:
       do stuff
   i = i + 1 

I have read that this isnt very "pythonic" at all , and I actually find myself using this type of code alot whenever I have to iterate over stuff , I found the enumerate function in Python that I think I am supposed to use but I am not sure how I can write similar code using enumerate instead? Another question I wanted to ask was when using enumerate does it effectively operate in the same way or does it do comparisons in parallel?

In my example code:

if myList[i] == something:

With enumerate will this check all values at the same time or still loop through one by one?

Sorry if this is too basic for the forum , just trying to wrap my head around it so I can drill "pythonic" code while learning.


Solution

  • In general, this is sufficient:

    for item in myList:
        if item == something:
            doStuff(item)
    

    If you need indices:

    for index, item in enumerate(myList):
        if item == something:
            doStuff(index, item)
    

    It does not do anything in parallel. It basically abstracts away all the counting stuff you're doing by hand in C++, but it does pretty much exactly the same thing (only behind the scenes so you don't have to worry about it).