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.

00:10 Say you want an iterator over all the even numbers. A generator with an infinite while loop does the trick. It starts at zero, yields the current number, adds two, and repeats forever.

00:22 That works, but with itertools, you can get the same sequence in one short line, without doing any arithmetic yourself. count() does exactly what it sounds like.

00:35 Create a counter. Take its first five values, and it counts from zero. Give it a step of two, and you have the even numbers.

00:47 Start at one with the same step, and you get the odd numbers.

00:54 count() even works with floats.

00:57 Starting at a half and stepping by three quarters works just fine.

01:03 You might wonder what good an infinite sequence is, since you can never loop over all of it. Here’s one use. Pair count() with a list of three letters using zip(). count() offers zero, one, two, and so on forever.

01:15 But zip() stops as soon as the letters run out. So you get exactly three pairs, and you’ve numbered a list without a for loop and without knowing its length.

01:25 Here’s that pairing in the REPL, along with two more infinite iterators. zip() with count() works like the built-in enumerate().

01:34 repeat() returns the same object over and over. If you pass a second argument, it stops after that many times. Without the second argument, it repeats forever.

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

01:59 In this lesson, you created infinite iterators with count(), repeat(), and cycle(), and you used zip() to stop them.

02:07 Infinite iterators are safe because they’re lazy. 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.