Skip to content
Advertisement

itertools’ islice(count()) vs range()

Real quick one:

I just saw a tutorial where they show we can use itertools’ islice() and count() together like so:

for num in islice(count(), start, stop, step):
    print(num)

Is there any advantage in doing this instead of using range() ?

Advertisement

Answer

Is there any advantage in doing this instead of using range() ?

In this example there is no advantage and range would be the canonical solution.

itertools.islice becomes important if you have an arbitrary iterator (Especially which does not have random access behaviour like range). Let’s say you opened a file and want to ignore the first four lines and then print every second line. With islice this becomes simply:

with open(path, 'r') as f:
    for line in islice(f, start=5, stop=None, step=2):
        print(line)

One possible combination of islice with counter, which cannot be replaced with range, is if you have a non finishing loop (stop = None). Let’s say you want to print all prime numbers starting from three.

uneven_numbers = islice(count(), start=3, stop=None, step=2):
for num in uneven_numbers:
    if is_prime(num):
        print(num)

Here it es especially important that uneven_numbers is a generator and not a list (which would definitely use up your memory.)

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement