0 votes
in Python by

Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.

For example, let’s suppose there are two lists and you want to multiply their elements. There can be several ways of achieving this. One can be using the naive approach i.e by iterating through the elements of both the list simultaneously and multiply them. And another approach can be using the map function i.e by passing the mul operator as a first parameter to the map function and Lists as the second and third parameter to this function. Let’s see the time taken by each approach.

# Python program to demonstrate 

# iterator module 

import operator 

import time 

# Defining lists 

L1 = [1, 2, 3] 

L2 = [2, 3, 4] 

# Starting time before map 

# function 

t1 = time.time() 

# Calculating result 

a, b, c = map(operator.mul, L1, L2) 

# Ending time after map 

# function 

t2 = time.time() 

# Time taken by map function 

print("Result:", a, b, c) 

print("Time taken by map function: %.6f" %(t2 - t1)) 

# Starting time before naive 

# method 

t1 = time.time() 

# Calculating result usinf for loop 

print("Result:", end = " ") 

for i in range(3): 

print(L1[i] * L2[i], end = " ") 

# Ending time after naive 

# method 

t2 = time.time() 

print("\nTime taken by for loop: %.6f" %(t2 - t1)) 

Result: 2 6 12
Time taken by map function: 0.000005
Result: 2 6 12 
Time taken by for loop: 0.000014

In the above example, it can be seen that the time taken by map function is approximately half than the time taken by for loop. This shows that itertools are fast, memory-efficient tool.

...