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:



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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(itertools.islice(li, 1, 6, 2)))  

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.