![]() |
VOOZH | about |
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().
0 1 2 3 4
Explanation:
islice(iterable, start, stop, step)
Parameters:
Note: If only one number is given after iterable, it is treated as the stop value.
Example 1: This example selects elements from index 2 to index 6 (excluding 6) from a list.
[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.
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.
[9, 16, 25, 36]
Explanation: