Related Articles

# Python – Itertools.islice()

• Last Updated : 27 Feb, 2020

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().

## 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:

 `# 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``)))  `

Output:

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

Example 2:

 `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:

 `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.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up