🎓 A1Learner
🔍

Python itertools: Infinite & Combining

An infinite iterator is an iterator that never runs out of values.

Count with a stopping plan

count starts at 10 and steps by 2. islice takes only four values, so the print ends.

from itertools import count, islice

print(list(islice(count(10, 2), 4)))

Cycle through values

cycle repeats its sequence in order. islice stops the cycle after five values.

from itertools import cycle, islice

lights = cycle(["red", "green"])
print(list(islice(lights, 5)))

Repeat one value

repeat gives the same value each time. Give it a count, or bound it with islice.

from itertools import repeat, islice

print(list(islice(repeat("tick"), 3)))
print(list(repeat("tock", 2)))

Join and pick values

chain joins two lists into one stream. compress keeps only items marked True.

from itertools import chain, compress

print(list(chain([1, 2], [3, 4])))
names = ["Ada", "Bob", "Cy"]
keep = [True, False, True]
print(list(compress(names, keep)))

Drop and take while a test holds

dropwhile skips values while the test is true. takewhile keeps values while the test is true.

from itertools import dropwhile, takewhile

numbers = [1, 2, 8, 9, 3]
print(list(dropwhile(lambda x: x < 5, numbers)))
print(list(takewhile(lambda x: x < 5, numbers)))

Example

from itertools import cycle, count, islice

days = cycle(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])
numbers = count(1)
pairs = zip(numbers, days)
for number, day in islice(pairs, 10):
    print(f"Day {number}: {day}")

Key points

  • Infinite iterator: an iterator that never runs out of values
  • Use count(start, step) to count upward with no end
  • Use cycle(sequence) to repeat a sequence again and again
  • Use repeat(value) to give the same value again and again
  • Use islice(iterator, n) to take only the first n values
  • Use chain(a, b) to join iterables into one stream
  • Never print an infinite iterator directly

In this example, cycle repeats the seven day names. count starts at 1 and keeps rising. zip pairs each number with the next day name. islice takes only the first ten pairs. The loop prints one labelled line per pair. Day 8 starts the week again with Mon.

Note

Always bound it first with islice or a counted loop.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

How do you safely print values from count()?