islice
- Python course
- Intermediate
- Lesson 96/116
- 5 min
Learn slicing with islice.
islice
islice(iterable, stop) or islice(iterable, start, stop, step) takes a portion of an iterable. It is similar to list slicing but also works on iterators; it does not create an intermediate list.
Example: list(islice(range(10), 3)) returns [0, 1, 2]. list(islice(range(10), 2, 8, 2)) returns [2, 4, 6]. Negative indices are not supported; this is a restriction compared to list slicing.
Memory advantage
islice gives a memory advantage in large data streams. For example, while reading a file line by line, islice(file, 100) takes the first 100 lines without loading the whole file into memory.
Similarly, on infinite iterators islice(count(1), 10) safely takes the first 10 items. When wrapped with list() the result becomes a list; but using it directly in a loop keeps memory usage minimal.
Practice Take the first three with islice
Start with from itertools import islice. Take the first three items of range with result = list(islice(range(10), 3)). Then print with print(result).
Starter code
# Take the first three of range with isliceSample solution
# Take the first three of range with islice
from itertools import islice
result = list(islice(range(10), 3))
print(result)Expected output
[0, 1, 2]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is islice preferred?
- To slice iterators Correct answer
- When negative indices are needed
- Only on lists
- To create a new list
Explanation: islice slices iterators; it does not produce a list.
2 islice call
from itertools import islice
result = list(____(range(10), 3))
print(result)
from itertools import islice
result = list(islice(range(10), 3))
print(result)
Explanation: islice slices the iterator.
3 Match the islice parts
| Term | Meaning |
|---|---|
islice |
Slicing function |
range(10) |
Iterable |
stop |
End index |
step |
Step |