Python | enumerate in python

This tutorial explains how to use enumerate function. enumerate function in Python returns an enumerate object.The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument.

enumerate function syntax

   
enumerate(iterable, start=0)
    

enumerate function parameters

  • iterable: An object that supports iteration
  • start: Starting idex value of counter (optional defaults to 0)

enumerate method examples

Getting indexed list with enumerate
   
data = [{"scrip_cd" : 541336, "scripname" : "NNTC"},
{"scrip_cd" : 513377, "scripname" : "MMTC"},
{"scrip_cd" : 513677, "scripname" : "PTC"},
{"scrip_cd" : 512677, "scripname" : "ZTC"}
]

print(list(enumerate(data)))
 
Output
   
[(0, {'scrip_cd': 541336, 'scripname': 'NNTC'}), (1, {'scrip_cd': 513377, 'scripname': 'MMTC'}), (2, {'scrip_cd': 513677, 'scripname': 'PTC'}), (3, {'scrip_cd': 512677, 'scripname': 'ZTC'})]
 
Using start parameter with enumerate
   
data = [{"scrip_cd" : 541336, "scripname" : "NNTC"},
{"scrip_cd" : 513377, "scripname" : "MMTC"},
{"scrip_cd" : 513677, "scripname" : "PTC"},
{"scrip_cd" : 512677, "scripname" : "ZTC"}
]

print(list(enumerate(data, start=2)))
 
Output
   
[(2, {'scrip_cd': 541336, 'scripname': 'NNTC'}), (3, {'scrip_cd': 513377, 'scripname': 'MMTC'}), (4, {'scrip_cd': 513677, 'scripname': 'PTC'}), (5, {'scrip_cd': 512677, 'scripname': 'ZTC'})]
 
Getting index of iterable using enumerate
   
data = [{"scrip_cd" : 541336, "scripname" : "NNTC"},
{"scrip_cd" : 513377, "scripname" : "MMTC"},
{"scrip_cd" : 513677, "scripname" : "PTC"},
{"scrip_cd" : 512677, "scripname" : "ZTC"}
]

for count, d in enumerate(data):
    print(count, d)
 
Output
   
0 {'scrip_cd': 541336, 'scripname': 'NNTC'}
1 {'scrip_cd': 513377, 'scripname': 'MMTC'}
2 {'scrip_cd': 513677, 'scripname': 'PTC'}
3 {'scrip_cd': 512677, 'scripname': 'ZTC'}
 
Getting items at even index using enumerate
   
data = [{"scrip_cd" : 541336, "scripname" : "NNTC"},
{"scrip_cd" : 513377, "scripname" : "MMTC"},
{"scrip_cd" : 513677, "scripname" : "PTC"},
{"scrip_cd" : 512677, "scripname" : "ZTC"}
]

for count, d in enumerate(data):
    if count % 2 == 0:
        print(count, d)
 
Output
   
0 {'scrip_cd': 541336, 'scripname': 'NNTC'}
2 {'scrip_cd': 513677, 'scripname': 'PTC'}
 
Getting items at odd index using enumerate
   
data = [{"scrip_cd" : 541336, "scripname" : "NNTC"},
{"scrip_cd" : 513377, "scripname" : "MMTC"},
{"scrip_cd" : 513677, "scripname" : "PTC"},
{"scrip_cd" : 512677, "scripname" : "ZTC"}
]

for count, d in enumerate(data):
    if count % 2:
        print(count, d)
 
Output
   
1 {'scrip_cd': 513377, 'scripname': 'MMTC'}
3 {'scrip_cd': 512677, 'scripname': 'ZTC'}
 

Follow US on Twitter: