The itertools module in Python provides a collection of tools for working with iterators, which are objects that can be iterated over (i.e., you can use a for loop to iterate over the items in an iterator). itertools provides a variety of functions that can be used to create, combine, and manipulate iterators in various ways.
Here are a few examples of commonly used functions from the itertools module:
itertools.chain(): This function takes one or more iterators as input and returns a single iterator that contains all of the items from the input iterators in sequence. For example:
import itertoolsa = [1, 2, 3]b = ['a', 'b', 'c']c = itertools.chain(a, b)for item in c: print(item) |
Output:
23abc |
itertools.product(): This function takes one or more iterables as input and returns an iterator that generates tuples containing all possible combinations of the input iterables. For example:
import itertoolsa = [1, 2]b = ['x', 'y', 'z']c = itertools.product(a, b)for item in c: print(item) |
Output:
(1, 'x')(1, 'y')(1, 'z')(2, 'x')(2, 'y')(2, 'z') |
itertools.combinations(): This function takes an iterable and an integer r as input and returns an iterator that generates tuples containing all possible combinations of r elements from the input iterable. For example:
import itertoolsa = [1, 2, 3]c = itertools.combinations(a, 2)for item in c: print(item) |
Output:
(1, 2)(1, 3)(2, 3) |
These are just a few examples of the many functions provided by the itertools module. By using these functions, you can create and manipulate iterators in powerful and flexible ways that can simplify your code and make it more efficient.