In this lesson, you’ll learn about the
itertools module. This module helps you create iterators for efficient looping:
>>> import itertools as it >>> rep = it.repeat(1) >>> next(rep) 1 >>> next(rep) 1
You’ll also learn about:
itertools.cycle, which infinitely cycles through iterables
itertools.permutations, which finds all the permutations (order matters)
itertools.combinations, which finds all the combinations (order does not matter)
You can check out the Python documentation on the
Let’s see how you might use this. Let’s say we wanted to create a list of 0 through 10 and square each number. Instead of doing a list comprehension, you could use the built-in
map() and then the built-in
pow() function, pass in
range(10), and then pass in our
itertools.repeat(2) This will create a
map object, and then
list() under the hood will call the
next() method on our
map object, and then return a list of 0 through 10—not including 10—squared.
You could change this to
4, or something like this. It’s just a easy way to have a constant stream of numbers that you need to keep accessing over and over in some sort of
There’s also another useful method,
itertools.cycle(). It’ll take an iterable and return an iterator that will loop through the iterable infinite number of times. It does not take in an optional argument, so this will actually go forever. So, let’s do
alternating_ones, which is the cycle of
-1. So, sometimes in an interview, you need some sort of infinite sequence—either of a constant number, or have maybe a sequence of numbers that you need to keep repeating over and over until some condition happens.
03:11 You might want to ask your interviewer if it’s okay to use these built-in functions because sometimes they want you to implement it from scratch. There are many examples online how to do that, but sometimes it’s really useful to do this maybe in a coding challenge, or if your interviewer just wants you to get the permutations and wants you to do some more complex logic on them.
There are a ton more functions in the
itertools module and I’ll link them all below. In the next video, you’ll learn about the
functools module, which includes a lot of useful higher order functions and decorators such as the higher order function
reduce() and the decorators
Become a Member to join the conversation.