Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

itertools islice method and start argument

Tags:

python

The documentation of itertools.islice says:

Make an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped.

Usage says:

islice('ABCDEFG', 2) --> A B
islice('ABCDEFG', 2, 4) --> C D

Shouldn't the first version return CDEFG ... skipping first two elements that is AB

like image 693
Bharat Jain Avatar asked Jul 24 '26 19:07

Bharat Jain


1 Answers

You're misreading. It has two call profiles:

itertools.islice(iterable, stop)
itertools.islice(iterable, start, stop[, step])

If you only pass two arguments, the second argument is the stop argument, as if you passed 0 as the start argument. To get the behavior you expected, you'd do:

islice('ABCDEFG', 2, None)

But understand that this is inefficient for large start values; under the hood, islice is iterating and discarding until it reaches the desired start position, you haven't bypassed the work of iterating (just optimized it a bit by doing it at the C layer in CPython).

like image 71
ShadowRanger Avatar answered Jul 26 '26 07:07

ShadowRanger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!