Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Generating Infinite Sequences

00:00 In this lesson, you’ll create iterators that never run out, with count(), repeat(), and cycle(), and you’ll see why an endless iterator can be useful. Say you want an iterator over all the even numbers.

00:14 A generator with an infinite while loop does the trick. It starts at zero, yields the current number, adds two, and repeats forever. That works, but with itertools, you can get the same sequence in one short line, without doing any arithmetic yourself.

00:31 count() does exactly what it sounds like. Create a counter.

00:38 Take its first five values, and it counts from zero. Give it a step of two, and you have the even numbers. Start at one with the same step, and you get the odd numbers.

00:56 count() even works with floats.

01:00 Starting at a half and stepping by three quarters works just fine. You might wonder what good an infinite sequence is, since you can never loop over all of it.

01:11 Here’s one use. Pair count() with a list of three letters using zip(). count() offers zero, one, two, and so on, forever. But zip() stops as soon as the letters run out.

01:21 So you get exactly three pairs, and you’ve numbered a list without a for loop and without knowing its length. Here’s that pairing in the REPL, along with two more infinite iterators.

01:33 zip() with count() works like the built-in enumerate(). repeat() returns the same object over and over. If you pass a second argument, it stops after that many times.

01:45 Without the second argument, it repeats forever.

01:52 cycle() loops over an iterable, and when it reaches the end, it starts again from the beginning. So cycling over one and minus one gives you an alternating sequence.

02:03 In this lesson, you created infinite iterators with count(), repeat(), and cycle(), and you used zip() to stop them. Infinite iterators are safe because they’re lazy.

02:14 They only produce a value when you ask for one. Next up, you’ll meet accumulate(), which turns a sequence into running totals.

Become a Member to join the conversation.