Open In App
Related Articles

Python – Itertools.islice()

Improve Article
Improve
Save Article
Save
Like Article
Like

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.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 19 Feb, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials