Iterator Functions in Python | Set 2 (islice(), starmap(), tee()..)
Last Updated :
04 Feb, 2020
Iterator Functions in Python | Set 1
1. islice(iterable, start, stop, step) :- This iterator
selectively prints the values mentioned in its iterable container passed as argument. This iterator takes
4 arguments, iterable container, starting pos., ending position and step.
2. starmap(func., tuple list) :- This iterator takes a
function and tuple list as argument and returns the
value according to the function from each tuple of list.
Python
# Python code to demonstrate the working of
# islice() and starmap()
# importing "itertools" for iterator operations
import itertools
# initializing list
li = [2, 4, 5, 7, 8, 10, 20]
# initializing tuple list
li1 = [ (1, 10, 5), (8, 4, 1), (5, 4, 9), (11, 10 , 1) ]
# using islice() to slice the list acc. to need
# starts printing from 2nd index till 6th skipping 2
print ("The sliced list values are : ",end="")
print (list(itertools.islice(li,1, 6, 2)))
# using starmap() for selection value acc. to function
# selects min of all tuple values
print ("The values acc. to function are : ",end="")
print (list(itertools.starmap(min,li1)))
Output:
The sliced list values are : [4, 7, 10]
The values acc. to function are : [1, 1, 4, 1]
3. takewhile(func, iterable) :- This iterator is opposite of dropwhile(), it prints the values
till the function returns false for 1st time.
4. tee(iterator, count) :- This iterator
splits the container into a number of iterators mentioned in the argument.
Python
# Python code to demonstrate the working of
# takewhile() and tee()
# importing "itertools" for iterator operations
import itertools
# initializing list
li = [2, 4, 6, 7, 8, 10, 20]
# storing list in iterator
iti = iter(li)
# using takewhile() to print values till condition is false.
print ("The list values till 1st false value are : ",end="")
print (list(itertools.takewhile(lambda x : x%2==0,li )))
# using tee() to make a list of iterators
# makes list of 3 iterators having same values.
it = itertools.tee(iti, 3)
# printing the values of iterators
print ("The iterators are : ")
for i in range (0,3):
print (list(it[i]))
Output:
The list values till 1st false value are : [2, 4, 6]
The iterators are :
[2, 4, 6, 7, 8, 10, 20]
[2, 4, 6, 7, 8, 10, 20]
[2, 4, 6, 7, 8, 10, 20]
5. zip_longest( iterable1, iterable2, fillval.) :- This iterator prints the
values of iterables alternatively in sequence. If one of the iterables is printed fully,
remaining values are filled by the values assigned to fillvalue.
Python
# Python code to demonstrate the working of
# zip_longest()
# importing "itertools" for iterator operations
import itertools
# using zip_longest() to combine two iterables.
print ("The combined values of iterables is : ")
print (*(itertools.zip_longest('GesoGes','ekfrek',fillvalue='_' )))
Output:
The combined values of iterables is :
('G', 'e') ('e', 'k') ('s', 'f') ('o', 'r') ('G', 'e') ('e', 'k') ('s', '_')
Combinatoric Iterators
1. product(iter1, iter2) :- This iterator prints the
cartesian product of the two iterable containers passed as arguments.
2. permutations(iter, group_size) :- This iterator prints all
possible permutation of all elements of iterable. The
size of each permuted group is
decided by group_size argument.
Python
# Python code to demonstrate the working of
# product() and permutations()
# importing "itertools" for iterator operations
import itertools
# using product() to print the cartesian product
print ("The cartesian product of the containers is : ")
print (list(itertools.product('AB','12')))
# using permutations to compute all possible permutations
print ("All the permutations of the given container is : ")
print (list(itertools.permutations('GfG',2)))
Output:
The cartesian product of the containers is :
[('A', '1'), ('A', '2'), ('B', '1'), ('B', '2')]
All the permutations of the given container is :
[('G', 'f'), ('G', 'G'), ('f', 'G'), ('f', 'G'), ('G', 'G'), ('G', 'f')]
3. combinations(iterable, group_size) :- This iterator prints
all the possible combinations(without replacement) of the container passed in arguments in the
specified group size in
sorted order.
4. combinations_with_replacement(iterable, group_size) :- This iterator prints
all the possible combinations(with replacement) of the container passed in arguments in the
specified group size in
sorted order.
Python
# Python code to demonstrate the working of
# combination() and combination_with_replacement()
# importing "itertools" for iterator operations
import itertools
# using combinations() to print every combination
# (without replacement)
print ("All the combination of container in sorted order(without replacement) is : ")
print (list(itertools.combinations('1234',2)))
# using combinations_with_replacement() to print every combination
# with replacement
print ("All the combination of container in sorted order(with replacement) is : ")
print (list(itertools.combinations_with_replacement('GfG',2)))
Output:
All the combination of container in sorted order(without replacement) is :
[('1', '2'), ('1', '3'), ('1', '4'), ('2', '3'), ('2', '4'), ('3', '4')]
All the combination of container in sorted order(with replacement) is :
[('G', 'G'), ('G', 'f'), ('G', 'G'), ('f', 'f'), ('f', 'G'), ('G', 'G')]
Infinite Iterators
1. count(start, step) :- This iterator
starts printing from the "start" number and prints infinitely. If steps are mentioned, the numbers are skipped else step is 1 by default.
Example :
iterator.count(5,2) prints -- 5,7,9,11...infinitely
2. cycle(iterable) :- This iterator prints all values in order from the passed container. It restarts
printing from beginning again when all elements are printed in a cyclic manner.
Example :
iterator.cycle([1,2,3,4]) prints -- 1,2,3,4,1,2,3,4,1...infinitely
3. repeat(val, num) :- This iterator
repeatedly prints the passed value infinite number of times. If num. is mentioned, them till that number.
Python
# Python code to demonstrate the working of
# repeat()
# importing "itertools" for iterator operations
import itertools
# using repeat() to repeatedly print number
print ("Printing the numbers repeatedly : ")
print (list(itertools.repeat(25,4)))
Output:
Printing the numbers repeatedly :
[25, 25, 25, 25]
Similar Reads
Operator Functions in Python | Set 2
Operator Functions in Python | Set 1 More functions are discussed in this article. 1. setitem(ob, pos, val) :- This function is used to assign the value at a particular position in the container. Operation - ob[pos] = val 2. delitem(ob, pos) :- This function is used to delete the value at a particul
5 min read
Operator Functions in Python | Set 1
Python has predefined functions for many mathematical, logical, relational, bitwise etc operations under the module "operator". Some of the basic functions are covered in this article. 1. add(a, b) :- This function returns addition of the given arguments. Operation - a + b. 2. sub(a, b) :- This func
5 min read
Matplotlib.axis.Tick.is_transform_set() function in Python
Matplotlib is a library in Python and it is numerical â mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. Matplotlib.axis.Tick.is_transform_set() Function The Tick.is_transform_set() fu
2 min read
Matplotlib.axis.Axis.is_transform_set() function in Python
Matplotlib is a library in Python and it is numerical â mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. matplotlib.axis.Axis.is_transform_set() Function The Axis.is_transform_set() fu
1 min read
Inplace Operators in Python | Set 2 (ixor(), iand(), ipow(),â¦)
Inplace Operators in Python | Set 1(iadd(), isub(), iconcat()â¦) More functions are discussed in this articles. 1. ixor() :- This function is used to assign and xor the current value. This operation does "a^ = b" operation. Assigning is not performed in case of immutable containers, such as strings,
3 min read
What is the send Function in Python Generators
Python generators are a powerful feature that allows for efficient iteration over potentially large datasets without the need to load everything into memory at once. A generator is a special type of iterable that uses the yield keyword to produce a sequence of values, one at a time. In addition to t
4 min read
Inplace Operators in Python | Set 1 (iadd(), isub(), iconcat()...)
Python in its definition provides methods to perform inplace operations, i.e. doing assignments and computations in a single statement using an operator module. Example x += y is equivalent to x = operator.iadd(x, y) Inplace Operators in PythonBelow are some of the important Inplace operators in Pyt
3 min read
Python Yield And Return In Same Function
Python, a versatile and powerful programming language, offers developers various tools and features to enhance code readability and efficiency. One such feature is the combination of yield and return statements within the same function. In this article, we will explore some commonly used methods whe
3 min read
SymPy | Subset.iterate_binary() in Python
Subset.iterate_binary() : iterate_binary() is a sympy Python library function that iterates over the binary subsets by k steps. Value of 'k' can be positive or negative. Syntax : sympy.combinatorics.subset.Subset.iterate_binary() Return : iterates over the binary subsets by k steps Code #1 : iterate
1 min read
Infinite Iterators in Python
Iterator in Python is any python type that can be used with a âfor in loopâ. Python lists, tuples, dictionaries, and sets are all examples of inbuilt iterators. But it is not necessary that an iterator object has to exhaust, sometimes it can be infinite. Such type of iterators are known as Infinite
2 min read