Islice function and stream in Python version

#1

Hi:

I have a question about itertools.islice(stream,k) function. In python book 5.13 (sampling online data), heaps bootcamp, and 10.3 (sort an almost-sorted array), the book uses itertools.islice to a sequence (or stream). After this operation, the solution uses “for x in sequence” to fetch remaining elements of the sequence (or stream).

As far as I searched, the itertools.islice(stream,k) function does not delete any element of an iterator. How come that you can fetch “remaining elements” but not “from the very beginning” of the sequence after using islice function?

Thanks.

0 Likes

#2

Hi @helloworld,

itertools.islice(stream, k) does consume the first k elements. You can use Python interpreter to try that by yourself. We have http://epijudge.com/ for readers to test your program with test data, and you will be able to verify that there as well.

0 Likes

#3

Hi @tsunghsienlee:

I tried the following code:

from itertools import islice
A = [0,1,2,3,4,5,6,7,8,9]
slice = islice(A, 5)
print(list(slice))
for remaining_item in A:
print(remaining_item)

The result is:

[0, 1, 2, 3, 4]
0
1
2
3
4
5
6
7
8
9

Does it indicate that islice() function did NOT consume elements in A? Did I get anything wrong?

Thanks.

0 Likes

#4

stream is not a list but an iterator. You can verify that, and that is the reason I said using http://epijudge.com/ you will find what is going on.

0 Likes

#5

I got it, thanks so much!

0 Likes