Saturday, November 23, 2024
Google search engine
HomeLanguagesPython – Itertools.islice()

Python – Itertools.islice()

In Python, Itertools is the inbuilt module that allows us to handle the iterators in an efficient way. They make iterating through the iterables like lists and strings very easily. One such itertools function is islice(). Note: For more information, refer to Python Itertools

islice() function

This iterator selectively prints the values mentioned in its iterable container passed as an argument. Syntax:

islice(iterable, start, stop, step)

Example 1: 

Python3




# Python program to demonstrate
# the working of islice
 
from itertools import islice
 
 
# Slicing the range function
for i in islice(range(20), 5):
    print(i)
     
     
li = [2, 4, 5, 7, 8, 10, 20]
 
# Slicing the list
print(list(islice(li, 1, 6, 2))) 


Output:

0
1
2
3
4
[4, 7, 10]

Example 2: 

Python3




from itertools import islice
 
 
for i in islice(range(20), 1, 5):
    print(i)


Output:

1
2
3
4

Here we have provide the three-parameter that is range(), 1 and 5. So the first parameter that is iterable as range and second parameter 1 will be considered as start value and 5 will be considered as stop value. Example 3: 

Python3




from itertools import islice
 
 
for i in islice(range(20), 1, 5, 2):
    print(i)


Output:

1
3

Here we provide the four-parameter that is range() as iterable, 1, 5 and 2 as stop value. So the first parameter that is iterable as range and second parameter 1 will be considered as start value and 5 will be considered as stop value and 2 will be considered as step value of how many steps to skip while iterating values.

RELATED ARTICLES

Most Popular

Recent Comments