Python Iterate Array

Iterate array elements using enumerate method

This is predefined function in python which adds counter or index to the array.
It allows to loop over array with index.
#!/usr/bin/python                                                               
                                                                                
list_arr = [10, 20, 30, 40, 50]                                                 
                                                                                
for index, val in enumerate(list_arr):                                          
    print("index: %d -> val: %d" % (index, val))  
Output:
$ python for_enumerate.py 
index: 0 -> val: 10
index: 1 -> val: 20
index: 2 -> val: 30
index: 3 -> val: 40
index: 4 -> val: 50
Even there is an optional parameter in enumerate method to specify the starting index.
#!/usr/bin/python                                                               
                                                                                
list_arr = [10, 20, 30, 40, 50]                                                 
                                 
# start index is 1 here                                               
for index, val in enumerate(list_arr, 1):                                        
    print("index: %d -> val: %d" % (index, val))
Output:
index: 1 -> val: 10
index: 2 -> val: 20
index: 3 -> val: 30
index: 4 -> val: 40
index: 5 -> val: 50

Iterate array elements using range and len method

#!/usr/bin/python                                                               
                                                                                
list_arr = [10, 20, 30, 40, 50]                                                 
                                                                                
for index in range(len(list_arr)):                                              
    print("index: %d -> val: %d" % (index, list_arr[index]))  
Output:
$ python for_range.py 
index: 0 -> val: 10
index: 1 -> val: 20
index: 2 -> val: 30
index: 3 -> val: 40
index: 4 -> val: 50

Iterate array elements using xrange and len method

#!/usr/bin/python                                                               
                                                                                
list_arr = [10, 20, 30, 40, 50]                                                 
                                                                                
for index in xrange(len(list_arr)):                                             
    print("index: %d -> val: %d" % (index, list_arr[index]))  
Output:
$ python test_xrange.py
index: 0 -> val: 10
index: 1 -> val: 20
index: 2 -> val: 30
index: 3 -> val: 40
index: 4 -> val: 50

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^