slicing an Iterator

Posted by Afsal on 10-May-2024

Hi Pythonistas!

Today we are learning how to slice an iterator properly?. Common mistakes we are making while slicing an iterator is first converting the iterator to a normal list and slicing the list. Issue with this approach is that the memory efficiency of the generator cannot be used. This can be done using itertools. Let us learn by an example.

Normal way

In [2]: a = range(100)

In [3]: a

Out[3]: range(0, 100)

In [4]: sliced_array = list(a)[10:25]

In [5]: sliced_array

Out[5]: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]

In [6]:

Correct way

In [11]: import itertools

In [12]: a

Out[12]: range(0, 100)

In [13]: sliced_generator = itertools.islice(a, 10, 25)

In [14]: sliced_generator

Out[14]: <itertools.islice at 0x7be1df65ba60>

In [15]: for i in sliced_generator:

...: print(i)

...:

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

In [16]:

We can see that in the second example output is generator. So it will be memory efficient. I hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in