Skip to content Skip to sidebar Skip to footer

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: ' <&

Solution 1:

In general, this is sufficient:

for item in myList:ifitem==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).

Solution 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 = 0while i < len(myList):
   if myList[i] == something:
       dostuffi= 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:
    ifitem== something:
        do stuff

Post a Comment for "Understanding Pythons Enumerate"