Using iteration effectively in Python



Following are the different ways to use iterators. 

C-style approach This approach requires prior knowledge of the total number of iterations.

# C style list items access

cars = [ "Aston" , "Audi" , "McLaren" ]

i = 0

while (i & lt; len (cars)):

print cars [i]

  i + = 1

Output:

 Aston Audi McLaren 

Important points:

  • This style of looping is rarely used by python programmers.
  • This four-step approach does not lend itself to compactness with a single-view looping construct.
  • This is also error prone in large scale programs or projects.
  • Python has no C-style for looping , i.e. a loop similar to for (int i = 0; i & lt; n; i ++)

Using the for-in style (or for each ):
This style is used in python containing list iterator, dicton, n-dimensional arrays, etc. The iterator fetches each component and prints the data during cycle. The iterator is automatically incremented / decremented in this construct.

# Access elements with a for-in loop

 

cars = [ " Aston " , " Audi " , "McLaren" ]

for x in cars:

print x

Exit:

 Aston Audi McLaren 

See this for more examples of different data types.

Indexing Using Range: We can also index using range () in Python.

# Access elements using indexes and for-in

 

cars = [ "Aston" , "Audi" , "McLaren" ]

for i in range ( len (cars)):

  print cars [i]

Exit :

 Aston Audi McLaren  

Enumerate:
Enumerate — it is a built-in Python function that takes input as an iterator, list, etc., and returns a tuple containing the index and that index`s data in the iterator sequence. For example, enumerate (cars), returns an iterator that will return (0, cars [0]), (1, cars [1]), (2, cars [2]), and so on.

# Accessing elements with enumerate ()

  

cars = [ "Aston" , "Audi" , "McLaren" ]

for i, x in enumerate (cars):

print ( x)

  Output:

 Aston Audi McLaren 

Below solution also works.

# Accessing enumerate () elements and indices

 

cars = [ "Aston" , "Audi" , "McLaren" ]

for x in enumerate (cars):

  print (x [ 0 ], x [ 1 ])

Exit :

 (0, `Aston`) (1,` Audi`) (2, `McLaren`) 

We can also directly print the return value of enumerate () to see what it returns.

# Print the return value of enumerate ()

 

cars = [ "Aston" , "Audi" , "McLaren" ]

print enumerate (cars)

Output:

 [(0, `Aston`), (1,` Audi`), (2, `McLaren`)] 

Enumerate takes a start parameter, which is set to zero by default. We can change this parameter to whatever value we like. In the code below, we have used the beginning as 1.

# demonstration of using the beginning in an enumeration

  

cars = [ "Aston" , "Audi" , "McLaren" ]

for x in enumerate (cars, start = 1 ):

print (x [ 0 ], x [ 1 ])

Output:

 (1, `Aston`) (2, `Audi`) (3,` McLaren `) 

enumerate () helps in building a solution for accessing each item of data in an iterator and retrieving the index of each item.

Loop extensions:
i) Two iterators for one looping construct: in this case the list and dictionary must be used for each iteration in one looping block using the enumeration function. Let`s see an example.

# Two separate lists

cars = [ " Aston " , "Audi" , "McLaren" ]

accessories = [ "GPS kit" , "Car repair-tool kit" ]

 
# The only dictionary contains prices for cars and
# its accessories.
# The first three products store car prices and 
# The next two things store the prices of accessories.

prices = { 1 : "570000 $" , 2 : "68000 $" , 3 : "450000 $" ,

4 : "8900 $" , 5 : " 4500 $ " }

  
# Print car prices

for index, c in enumerate (cars, start = 1 ):

print "Car:% s Price:% s" % (c, prices [index])

 
# Print accessory prices

for index, a in enumerate (accessories, start = 1 ):

print ( "Accessory:% s Price:% s "

  % (a , prices [index + len (cars)]))

Exit:

 Car: Aston Price: 570,000 $ Car: Audi Price: 68,000 $ Car: McLaren Price: 450,000 $ Accessory: GPS kit Price: 8900 $ Accessory: Car repair tool kit Price: 4500 $ 

ii) zip function (both iterators must be used in a single looping construct):
This function is useful for combining the same iterator types (list-list or dict dict, etc.) in data items in i-th position. It uses the shortest length of these input iterators. Other elements of longer iterators are skipped. In the case of empty iterators, it returns No output.

For example, using zip for two lists (iterators) helped to combine one machine and its required accessory.

# Python zip demo

  
# Two separate lists

cars = [ "Aston" , "Audi" , "McLaren" ]

accessories = [ "GPS" , " Car Repair Kit "

"Dolby sound kit" ]

 
# Merge lists and print

for c, a in zip (cars, accessories):

print "Car:% s, Accessory required:% s"

% (c, a)

Exit:

 Car: Aston, Accessory required: GPS Car: Audi, Accessory required : Car Repair Kit Car: McLaren, Accessory required: Dolby sound kit 

The downside of these iterators from the zip function is known as unzipping with using the "*" operator.

Using the enumeration function and the zip function helps to achieve an efficient extension of iterative logic in python and solves many more sub-tasks of a huge task or problem.

# Demo Python program unzip (reverse
# zip) using * with zip function

 
# Unpack lists

l1, l2 = zip ( * [( `Aston` , `GPS` ), 

  ( ` A udi` , `Car Repair` ), 

( `McLaren` , `Dolby sound kit`

])

 
# Print unpacked lists

print (l1)

print (l2)

Exit:

 (`Aston`,` Audi`, `McLaren`) (` GPS `,` Car Repair`, `Dolby sound kit`) 

Links:
1. https://docs.python.org/2/library/functions.html#enumerate
2. < a href = https://docs.python.org/2/library/functions.html#zip> https://docs.python.org/2/library/functions.html#zip

This article contributed by Krishnasagar Podadraj . If you like Python.Engineering and would like to contribute, you can also write an article and mail it to [email protected] See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.