1

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.

user4759923
  • 531
  • 3
  • 12
bengerman
  • 113
  • 2
  • 10
  • 1
    Have you checked out [this thread](http://stackoverflow.com/questions/22171558/what-does-enumerate-mean)? – Dan Apr 14 '15 at 05:34
  • Note that nowadays even in C++ you don't need to manually count indices when iterating over containers. – mkrieger1 Apr 14 '15 at 15:40

2 Answers2

2

You don't need enumerate() at all in your example.

Look at it this way: What are you using i for in this code?

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

You only need it to access the individual members of myList, right? Well, that's something Python does for you automatically:

for item in myList:
    if item == something:
        do stuff
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
2

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

Amadan
  • 191,408
  • 23
  • 240
  • 301