May 26, 2021, 6:43 p.m.
Let's suppose there are two lists and you want to add their elements and at last index you will find the sum of all elements. You can also check max and min at a particular index. You can do it using a for loop, using map function or an efficient way of doing it is using itertools. Python provides various functions that works on iterators.
Let's suppose there are two lists and you want to add their elements and at last index you will find the sum of all elements. You can also check max and min at a particular index. You can do it using a for loop, using map function or an efficient way of doing it is using itertools. Python provides various functions that works on iterators.
To get next element:
import itertools
seq=["Ankit", "Deepak", "Kiran"]
cycle1= itertools.cycle(seq)
print(next(cycle1)) #Ankit
print(next(cycle1)) #Deepak
print(next(cycle1)) #Kiran
Counter:
import itertools
#itertools.count(start,step)
count1=itertools.count(100,10)
print(next(count1)) #100
print(next(count1)) #110
print(next(count1)) #120
print(next(count1)) #130
Accumulate:
It will return accumulated sum or accumulated results of other functions which is mentioned in the parameter.
import itertools
val=[10, 20, 30, 40, 50, 40, 30]
acc=itertools.accumulate(val,max)
print(list(acc))
#Output:
#[10, 20, 30, 40, 50, 50, 50]
You can use operator to perform different functions on accumulator like add, sub, lessthan greaterthan, mul.
Click here to know more about operators.
import itertools
import operator
val = [2, 3, 6]
acc = itertools.accumulate(val,operator.mul)
print(list(acc))
#Output:
#[2, 6, 36]