Change language

Iterator Functions in Python | Set 2 (islice (), starmap (), tee () ..)

1. islice (iterable, start, stop, step) : — this iterator selectively prints the values ​​referenced in its iterable container passed as an argument. This iterator takes 4 arguments, an iterative container, start position, end position, and stride.

2. starmap (func., List of tuples) : — This iterator takes a function and a list of tuples as an argument and returns a value according to the function from each tuple in the list.

# Python code to demonstrate how it works
# islice () and starmap ()

 
# import & quot; itertools & quot; for iterator operations

import itertools

 
# initializing list

li = [ 2 , 4 , 5 , 7 , 8 , 10 , 20 ]

  
# initialize the list of tuples

li1 = [( 1 , 10 , 5 ), ( 8 , 4 , 1 ), ( 5 , 4 , 9 ), ( 11 , 10 , 1 )]

  

  
# using islice () to slice the list according to ... need
# starts printing from 2nd index to 6th skip 2

print ( "The sliced ​​list values ​​are:" , end = "")

print ( list (itertools.islice (li, 1 , 6 , 2 )))

 
# using starmap () to select a value acc. function
# selects the minimum 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 the opposite of drop while (), it prints the values ​​ until the function returns false the first time.

4. tee (iterator, count) : — This iterator splits the container into multiple iterators mentioned in the argument.

# Python code to demonstrate how it works
# takewhile () and tee ()

 
# import & quot; itertools & quot; for iterator operations

import itertools

 
# initializing list

li = [ 2 , 4 , 6 , 7 , 8 , 10 , 20 ]

  
# save the list in an iterator

iti = iter (li)

  
# using takewhile () to print values ​​until the 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 list iterators
# makes a list of 3 iterators that have the same value.

it = itertools.tee (iti, 3 )

 
# printing iterator values ​​

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 the iterables one at a time . If one of the iterations is printed completely, the remaining values ​​are filled with the values ​​assigned to fillvalue .

# Python code to demonstrate how it works
# zip_longest ()

 
# import & quot; itertools & quot; for iterator operations

import itertools

 
# using zip_longest () to combine the two iterations.

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’, ’_’) 

Combinatorial 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 permutations of all elements of the iterable.  The size of each permutation group is determined by the group_size argument.

# Python- demo code
# product () and permutation ()

 
# import & quot; itertools & quot; for iterator operations

import itertools

 
# using product () to print a Cartesian product

print ( "The cartesian product of the containers is:" )

print ( list (itertools.product ( ’AB’ , ’ 12’ )))

 
# use 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 possible combinations (no 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 possible combinations (with replacement) of the container passed in arguments in the specified group size in sorted order.

# Python code to demonstrate how it works
# combination () and combination_with_replacement ()

 
# import & quot; itertools & quot; for iterator operations

import itertools

 
# use combinations () to print each combination
# (without replacements)

print ( "All the combination of container in sorted order (without replacement) is: " )

print ( list (itertools.combinations ( ’1234’ , 2 )))

 
# using combination_with_replacement () to print each 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 at "start" and prints indefinitely . If steps are mentioned, numbers are skipped, otherwise step is 1 by default.

Example:

 iterator.count (5,2) prints - 5,7,9,11 .. .infinitely 

2. loop (iterable) : — this iterator prints all values ​​in order from the passed container. It resumes printing from the beginning again when all items are cycled .

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 an infinite number of times. If a number is mentioned, they are up to that number.

# Python code to demonstrate how it works
# repeat ()

 
# import & quot; itertools & quot; for iterator operations

import itertools

 
# using repeat () to repeatedly print the number

print ( "Printing the numbers repeatedly:" )

print ( list (itertools.repeat ( 25 , 4 )))

Output:

 Printing the numbers repeatedly: [25, 25, 25, 25] 

This article courtesy of Manjeet Singh . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. 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.

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically