islice in Python
The islice() method is provided by itertools module in Python which is used to select elements from iterators based on the index of the elements. Islice() is similar to slicing in Python. The itertools module in Python gives access to iterating through iterables.
Syntax:
Itertools.islice (iterable, start, stop, step)
Parameter:
- Iterable: This is iterable.
- Start: starting point of the iteration.
- Stop: ending point of the iteration.
- Step: the number of elements to be skipped.
Important points:
- This method doesn't permit the passing of the negative values for start, stop, and step parameters.
- When the start is greater than zero, the elements from the iterable are skipped until the start is reached.
- The step default value is 1.
- If the value of stop is positive, the iteration stops at the positive value. If it's None, the iteration does not stop until the iterator is exhausted.
Code:
from itertools import islice
def islice_with_single_value(iterator, val):
print("islice(%s, %s) = %s" % (iterator, val, list(islice(iterator, val))))
def islice_with_start_stop(iterator, start, stop):
print("islice(%s, %s, %s) = %s" % (iterator, start, stop, list(islice(iterator, start, stop))))
def islice_with_start_stop_step(iterator, start, stop, step):
print("islice(%s, %s, %s, %s) = %s" % (iterator, start, stop, step, list(islice(iterator, start, stop, step))))
iterator = range(10)
val = 4
islice_with_single_value(iterator, val)
start = 5
stop = 10
islice_with_start_stop(iterator, start, stop)
step = 3
islice_with_start_stop_step(iterator, start, stop, step)
Output:
islice(range(0, 10), 4) = [0, 1, 2, 3]
islice(range(0, 10), 5, 10) = [5, 6, 7, 8, 9]
islice(range(0, 10), 5, 10, 3) = [5, 8]
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(islice(li, 1, 6, 2)))
Output:
0
1
2
3
4
[4, 7, 10]
In the case of the slice method, the start, stop, and step values can be negative, but this is not valid for the slicemethod; it returns a ValueError.