islice() is a function from Python’s built-in itertools module. It is used to slice an iterator without converting it into a list. Unlike normal slicing ([:]), it works directly on iterators like range(), generators or file objects. It returns selected elements one by one, making it memory-efficient and suitable for large data.
Example: In this example, we print the first 5 values from a range object using islice().
from itertools import islice
for i in islice(range(10), 5):
print(i)
Output
0 1 2 3 4
Explanation:
- range(10) creates numbers from 0 to 9.
- islice(range(10), 5) selects the first 5 elements.
- The loop prints values from 0 to 4.
Syntax
islice(iterable, start, stop, step)
Parameters:
- iterable: The iterator or iterable to slice.
- start(optional): Starting index.
- stop(not included): Ending index.
- step(optional): Number of elements to skip.
Note: If only one number is given after iterable, it is treated as the stop value.
Examples
Example 1: This example selects elements from index 2 to index 6 (excluding 6) from a list.
from itertools import islice
lst = [10, 20, 30, 40, 50, 60, 70]
print(list(islice(lst, 2, 6)))
Output
[30, 40, 50, 60]
Explanation: islice(lst, 2, 6) starts from index 2 and stops before index 6, returning the selected elements.
Example 2: This example selects elements from index 1 to 8 with a step of 2, meaning every second element is chosen.
from itertools import islice
for i in islice(range(10), 1, 8, 2):
print(i)
Output
1 3 5 7
Explanation: islice(range(10), 1, 8, 2) starts at index 1, stops before 8 and skips 2 steps each time, selecting alternate elements.
Example 3: This example uses islice() on a generator. The generator produces square numbers and we extract only a specific portion of those generated values without storing everything in memory.
from itertools import islice
def sq(n):
for i in range(n):
yield i * i
g = sq(10)
print(list(islice(g, 3, 7)))
Output
[9, 16, 25, 36]
Explanation:
- sq(10) generates squares from 0 to 81.
- islice(g, 3, 7) skips the first 3 generated values and returns elements from index 3 to 6.
- Since it works directly on the generator g, it does not store all values in memory.