Learn Python Enumerate the Easy Way

Hello Geeks! I hope all are doing great. So today in this article we will talk about the python enumerate() function. We will see how we can use it efficiently despite such a short topic. So, without wasting time, Let’s get started.

Eumerate()

While dealing with iterator objects or loops, sometimes we need to keep a record of iteration counts or loop counts. However, while working with loops we can define some variables to keep the count but is it an efficient way to achieve it? Although we can use it, python comes with an inbuilt function named enumerate() which deals with the iterations counts. enumerate() functions make our work easy not only for loops but also for iterables like lists. It adds a counter to the iterable object and returns it in the form of an enumerated object. To understand it more clearly we will take an example but before that let’s take a look at its syntax.

Syntax

enumerate(iterators, start)

  • iterators:– This is the object whose count we want to track.
  • start:- Integer from where we want to start counting.

Let’s move on to examples now.

Click here for NumPy tutorials: https://www.pythonpool.com/category/numpy/

Example 1 :- Enumerate functions on strings object

In this example, we will see how can we use enumerate function on string objects.

# Lets create a string
string1 = "pythonpool"

# Converting string to enumerted object
enumerated_object = enumerate(string1)

print(type(enumerated_object)) #Checking type of enumerated object
print(list(enumerated_object)) # printing enumerated object as list

Output:

<class 'enumerate'>
[(0, 'p'), (1, 'y'), (2, 't'), (3, 'h'), (4, 'o'), (5, 'n'), (6, 'p'), (7, 'o'), (8, 'o'), (9, 'l')]

Example 2 :- Enumerate functions on lists

In this example, we will see how can we use enumerate function on list objects.

# Lets create a list

list1 = ['python','enumerate','function']

# Converting the list to enumerated object
enumerated_object = enumerate(list1)

# Checking datatype of enumerated_object
print(type(enumerated_object))
print(list(enumerated_object))

Output:

<class 'enumerate'>
[(0, 'python'), (1, 'enumerate'), (2, 'function')]

Example 3 :- Enumerate functions for loops

list1 = ["Geeks", "on", "Pythonpool"]

for x in enumerate(list1):
  print(x)

Output:

(0, 'Geeks')
(1, 'on')
(2, 'Pythonpool')

Example 4 :- Enumerate functions on dictionary

# Creating dictionary
dictionary1 = {"a":10,"b":20,"c":30}

enumerated_object = enumerate(dictionary1.items())
print(list(enumerated_object))

Output:

[(0, ('a', 10)), (1, ('b', 20)), (2, ('c', 30))]

In the above example we have seen how can we print dictionary items as the enumerated objects.

Example 5 :- Enumerate start at 1 and 100

In the above examples, you can notice that all the iterations start from 0. However, It is possible to change that count too. It can be done using the second argument of the enumerate function. Let’s check it.

# Lets create a string
string1 = "pythonpool"

# Converting string to enumerted object and starting it with 1
enumerated_object = enumerate(string1,1)

# enumerated object strted from 100
enumerated_object2 = enumerate(string1,100)


print(type(enumerated_object)) #Checking type of enumerated object
print(list(enumerated_object)) # printing enumerated_object as list
print(list(enumerated_object2)) # printing enumerated_object2 as list

Output:

<class 'enumerate'>
[(1, 'p'), (2, 'y'), (3, 't'), (4, 'h'), (5, 'o'), (6, 'n'), (7, 'p'), (8, 'o'), (9, 'o'), (10, 'l')]
[(100, 'p'), (101, 'y'), (102, 't'), (103, 'h'), (104, 'o'), (105, 'n'), (106, 'p'), (107, 'o'), (108, 'o'), (109, 'l')]

Example 6:- Enumerate reverse

In this example, we see how can we reverse enumerated objects using the reverse function. But to apply reverse object we need to first convert into a list otherwise it raises an error as “enumerated object cannot be reversed”.

# Lets create a list

list1 = ['python','enumerate','function']

# Converting the list to enumerated object
reversed_enumerated_object = reversed(list(enumerate(list1)))
print(list(reversed_enumerated_object))

Output:

[(2, 'function'), (1, 'enumerate'), (0, 'python')]

Example 7:- Enumerate OrderedDict in python

from collections import OrderedDict

dictionary = OrderedDict({
    'a':10,
    'b':20,
    'c':30
})
print(dictionary)

# Converting dictionary as enumerated object using for loop
print
print("Printing ordered dictionary as enumerated object:")
for i,(j,k) in enumerate(dictionary.items()):
  print(i,j,k)

Output:

OrderedDict([('a', 10), ('b', 20), ('c', 30)])
Printing ordered dictionary as enumerated object
0 a 10
1 b 20
2 c 30

Example 8:- Enumerate over list of Tuples

tuple1 = [('a',10),('b',20),('c',30)]
for i,(j,k) in enumerate(tuple1):
  print(i,j,k)

Output

0 a 10
1 b 20
2 c 30

Example 9:- Enumerate Function in Jinja 2

from jinja2 import Template

>>> s = "{% for element in elements %}{{loop.index}} {% endfor %}"
>>> Template(s).render(elements=["a", "b", "c", "d"])

Output:

1 2 3 4 

Efficiency of Enumerate Method

Although, we can use both “range” or “enumerate” methods for the “for loop”. But there are several tests that suggest that enumerate method is slightly faster than the range method.

How to Enumerate modules in python 64bit

To enumerate modules in python 64bits, use the following codes:

from ctypes import *
from ctypes.wintypes import *
import sys


# const variable
# Establish rights and basic options needed for all process declartion / iteration
TH32CS_SNAPPROCESS = 2
STANDARD_RIGHTS_REQUIRED = 0x000F0000
SYNCHRONIZE = 0x00100000
PROCESS_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFF)
TH32CS_SNAPMODULE = 0x00000008
TH32CS_SNAPTHREAD = 0x00000004

class MODULEENTRY32(Structure):
    _fields_ = [ ( 'dwSize' , DWORD ) , 
                ( 'th32ModuleID' , DWORD ),
                ( 'th32ProcessID' , DWORD ),
                ( 'GlblcntUsage' , DWORD ),
                ( 'ProccntUsage' , DWORD ) ,
                ( 'modBaseAddr' , LONG ) ,
                ( 'modBaseSize' , DWORD ) , 
                ( 'hModule' , HMODULE ) ,
                ( 'szModule' , c_char * 256 ),
                ( 'szExePath' , c_char * 260 ) ]

CreateToolhelp32Snapshot= windll.kernel32.CreateToolhelp32Snapshot
Process32First = windll.kernel32.Process32First
Process32Next = windll.kernel32.Process32Next
Module32First = windll.kernel32.Module32First
Module32Next = windll.kernel32.Module32Next
GetLastError = windll.kernel32.GetLastError
OpenProcess = windll.kernel32.OpenProcess
GetPriorityClass = windll.kernel32.GetPriorityClass
CloseHandle = windll.kernel32.CloseHandle


try:
    ProcessID=22052
    hModuleSnap = DWORD
    me32 = MODULEENTRY32()
    me32.dwSize = sizeof( MODULEENTRY32 )
    #me32.dwSize = 5000
    hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, ProcessID )
    ret = Module32First( hModuleSnap, pointer(me32) )
    if ret == 0 :
        print 'ListProcessModules() Error on Module32First[%d]' % GetLastError()
        CloseHandle( hModuleSnap )
    global PROGMainBase
    PROGMainBase=False
    while ret :
        print me32.dwSize
        print me32.th32ModuleID
        print me32.th32ProcessID
        print me32.GlblcntUsage
        print me32.ProccntUsage
        print me32.modBaseAddr
        print me32.modBaseSize
        print me32.hModule
        print me32.szModule
        print me32.szExePath
        ret = Module32Next( hModuleSnap , pointer(me32) )
    CloseHandle( hModuleSnap )

except:
    print "Error in ListProcessModules"

FAQs on Python Enumerate

Is there an equivalent to the range-based ‘enumerate’ loop from python in modern C++?

No, there is not any equivalent to range-based enumerate loop in c++.

How to enumerate an object’s properties in python?

In order to do that follow the given code:

for property, value in vars(theObject).items(): print(property":", value)

What is faster, for loop using enumerate() or for loop using range() in python?

for loop using enumerate is slightly faster than for loop using r.ange function.

How can I enumerate all the possible n-long combinations of zeroes and ones in python

You can use itertools.product() to do that.

import itertools
length = 3
for thing in itertools.product([0, 1], repeat=length): print(thing)

How to enumerate the values of two python dictionary of dictionaries simultaneously

To do that we will use the zip() method. We first zip both dictionaries and then print key-value pairs for both. To do that use the following code.

d1 = {'a':5, 'b':6, 'c': 3}
d2 = {'a':6, 'b':7, 'c': 3}
for (k1,v1), (k2,v2) in zip(d1.items(), d2.items()):
  print (k1, v1)
  print (k2, v2)

Conclusion

So, today in this article we learned about the python enumerate function. We saw how iterators act on different python objects and how it works. After that, we have seen some examples covering the uses of enumerate function.

Hope this article helped you. Thank You!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments