# Itertools Module in Python with Examples

Itertool is one of the most amazing Python standard libraries. This specific library has pretty cool functions also, Python hence provides excellent documentation of the itertools.

In this article, we’ll read how and where it can be used.

### Python – Itertools()

As in Mathematics, the Cartesian Product of two sets is defined as the set of all ordered pairs (p, q) where p belongs to P and q belongs to Q. Itertools are used in the calculations of such numeric codes.

The itertools are also used in the various small operations of the codes which can easily be interpreted by the coder.

While in some cases, a user may enter a numeral and may not directly convert it in binary, in such cases itertools also act as an interface between the codes.

arr1 = [1, 2] arr2 = [5, 6] print((arr1, arr2))

**Output:**

### What are Itertools in Python?

Python Itertools is a library in Python generally consisting of multiple methods. These are used in various iterators to compute a fast and code efficient solution in the runtime.

Itertools.product() falls under the category called Combinatorial iterators of the Python itertools library for user-defined functions.

### What does itertools.product() do?

It is used to find the set or the product of any two binary numbers entered by the user. The itertools.product() can be used in two different ways as follow:

**itertools.product(*iterables, repeat=1)**

It returns the product of the entered numeric values as one. This can easily be interpreted by the coder.

**itertools.product(*iterables)**

It returns the cartesian product of all the numeric values without any manipulation in the code.

**Python Itertools Example:**

from itertools import product # this imports the function def thisistech(enter1, enter2): #this allows the two data variables return list(product(enter1, enter2)) if __name__ == "__main__": enter1 = [56] enter2 = [89] print(thisistech(enter1, enter2))

**Output:**

>>>

#### Python Itertools.chain(*iterables)

This makes the iterable position of the variables as binary digits which can be easily identified by the coder.

Technically, they are used for treating consecutive sequences as a single sequence. Its syntax is as follows:

def c(*iterables): for t in iterables: for element in t: yield element classmethod c.from_iterable(iterable)

**Alternate constructor for chain()**

A constructor chain is a default execution code in a loop using for while statements. This also helps the chain to create a multiple access code in one time.

**Syntax**

def from_iterable(iterables): for t in iterables: for element in t: yield element

#### itertools.combinations(iterable, r)

This gives the iterable element of the same list in the source code.

**Syntax**

def combinations(iterable, r):

p = tuple(iterable) n = len(p) #this inputs all the values from n to n-1 if r > n: return indices = range(r) #this changes the range of the values yield tuple(pl[i] for i in indices) while True: #a condition for reversed order is a must for i in reversed(range(r)): if indices[i] != i + n - r: break else: Return #it count the indices number indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pl[i] for i in indices)

#### itertools.combinations_with_replacement(iterable, r)

The combinatorial and permutable based calculations are generally based on this code. This also helps the user in combining multiple lists in one time also.

**Syntax**

def combinations_with_replacement(iterable, r):

p = tuple(iterable) n = len(p) if not n and r: return indices = [0] * r yield tuple(p[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != n - 1: break else: return indices[k:] = [indices[k] + 1] * (n - i) yield tuple(p[k] for i in indices)

#### itertools.compress(data, selectors)

This evaluates the compressed code as data and selectors which further adds in the execution of the code.

**Syntax**

def compress(data, selectors): return (d for data, s in izip(data, selectors) if s)

#### islice(iterable,stop)

This slices the list in two parts and creates a new list simultaneously.

**Syntax**

islice(iterable,start,stop [,step])

**Example of Python Itertools islice():**

from itertools import islice for thisistech in islice([50,89,90],900): print(thisistech)

**Output:**

89

90

>>>

#### itertools.count(start=0, step=1)

This makes the code iterable with any functional value as entered by the user and this by default takes the starting value as 1 and the ending value of the loop as 0.

**Syntax**

def count(start=0, step=1). n = start while True: yield n n += step

#### itertools.cycle(iterable)

This itertool creates a repetitive cycle of executing code in such a way, that it takes different values every time from the user.

**Syntax**

def c(iterable): saved = [] for element in iterable: yield element saved.append(element) while saved: for element in saved: yield element

#### itertools.dropwhile(predicate, iterable)

This dropdown the value as null, and if it has any calculations to do, then it takes the default value as one only.

**Syntax**

def dropwhile(predicate, iterable): iterable = iter(iterable) for i in iterable: if not predicate(x): yield i break for i in iterable: yield i

#### itertools.groupby(iterable[, key])

This groups the same additive elements in one part of the list and the rest in the other part.

**Syntax**

groups = [] uniquekeys = [] data = sorted(data, key=keyfunc) for i, g in groupby(data, keyfunc): groups.append(list(g)) uniquekeys.append(1) def __init__(self, iterable, key=None): if key is None: while self.key == self.tkey: self.value = next(self.it) self.key = self.keyfunc(self.currvalue) self.tgtkey = self.currkey

#### itertools.ifilter(predicate, iterable)

This as the name suggests, it predicts the iterable tools in the run time for the same code.

**Syntax**

def ifilter(predicate, iterable): if predicate is None: predicate = bool for i in iterable: if predicate(i): yield i

#### itertools.ifilterfalse(predicate, iterable)

This returns the false value of the statements. The execution which goes correct is treated as a null value.

**Syntax**

def ifilterfalse(predicate, iterable): if predicate is None: predicate = bool for i in iterable: if not predicate(i): yield i

#### itertools.izip(*iterables)

This simply zips the code like any other file which can only be extracted by a unique pin. Like zip() except that it returns an iterator instead of a list in the runtime.

**Syntax**

def izip(*iterables): iterators = map(iter, iterables) while iterators: yield tuple(map(next, iterators))

#### itertools.permutations(iterable[, r])

This performs a permutable iteration in a list, and also allows the user to do the same for 3 different lists in the runtime.

**Syntax**

indices = range(i) cycles = range(i, i-r, -1) yield tuple(pool[i] for i in indices[:r]) while i: for k in reversed(range(r)): cycles[k] -= 1 if cycles[k] == 0: indices[k:] = indices[k+1:] + indices[k:k+1] cycles[k] = i - k else: j = cycles[k] indices[k], indices[-j] = indices[-j], indices[k] yield tuple(pool[k] for i in indices[:r]) break else: return

#### itertools.repeat(object[, times])

A repeat object when provided with the number of times, repeats the code in such a manner that it has different arguments every time.

**Syntax**

def repeat(object, times=N): if times is N: while True: yield object else: for i in xrange(times): yield object

A very general repeat system is followed in the code, which allows the recursive execution of the same code in multiple run time.

#### itertools.starmap(function, iterable)

The starmap attribute is different from others as it works on the unique key elements of the list only.

**Syntax**

def starmap(function, iterable) for args in iterable: yield function(*args)

### Python grouper Recipe

A grouper recipe handles only one code at a time. It does not allow the execution of twoTarguments simultaneously in a code.

**Syntax**

>>> numbdef = [] >>> listfirst(better_grouper(nums, 2))

**Sequences of Numbers:** This signifies the sequence and series of display of the list. It can be of any mathematical type, but the coder needs to keep in mind that the only accepted value of this list should be an integer.

**Evens and Odds sequence:** This displays the sequence of even and odd numbers in a series.

**Code:**

thisistech=int(input("Number to check is : ")); if(thisistech%2==0): #it will return a number by dividing it by two print("Even") else: print("Odd")

**Output:**

Even

>>>

### Python Recurrence Relations

This as defined by name means recurring repetition of the key element in the main list. But it also signifies the calculated element is not replicated further. The best-known recurrence relation is the Fibonacci sequence.

**Code:**

def fibsnumb(): p,q = 0, 1 #define the fib while True: #this will check the entered number yield p p, q = p, q + p

#yield will act as a print statement

**Output:**

True

>>>

**1. First Order Recurrence Relations:**

This means it repeats only the first element of any list, the other elements as left as it is only.

**Syntax**

count_by_one = it.count(step=1)

**2. Second-Order Recurrence Relations:**

A second-order recurrence defines the unique list in a sorted way.

**Code:**

fibs = second #this will show error li(next(fibs) for _ in range(6))

**Output:**

**Intermission: Flattening A List of Lists**

This helps the user flatten the list and check its all elements one by one. This is also helpful in merging two lists with different data types for any relational databases also.

**Code:**

thisistech='1','2','3' for li in range (1,8): print(li)

**Output:**

2

3

4

5

6

7

>>>

### Python Maximum Gain and Loss

This displays the maxima and the minima of the data, or a graph logically by simply evaluating and comparing every element with the other element.

To determine the maximum gain or loss as a programming function, the coder can do this:

**Code:**

a=[34,56,78] p=max(a) print(p)

**Output:**

>>>

**Using next() function:** This attribute helps in moving from one element to the other in the same list.

**Code:**

import itertools I = "TechVidvan" #for i in range(I): print(I)

**Output:**

### Cloning sequences with tee()

This is a case of copying one list’s elements to the other list without the actual data change in final lists. In this case, the original sequence cannot be used more than once. Cloning is a special case of copying, it is done when the user decides to copy and save the previous data as it is in the new data table. Cloning does not allow the updation or ammendation of the data.

**Code:**

from itertools import * for n in THISISTECH: print('cloned: {}'.f(numbprint)) for B in THISISTECH: print('cloned1: {}'.f(numbprint))

**Output:**

### Accumulating Operations with accumulate()

To accumulate a function in the code one needs to copy the identifiers from the library and then execute the same in the code. Like adding the numbers to the previous value in the sequence within the run time for user-defined codes.

**Code:**

from itertools import * THISISTECH = accumulate(range(6)) for val in THISISTECH: print(val)

**Output:**

1

3

6

10

15

**filter items with takewhile():** This method helps the coder in identifying the unique value in the lists. It is also useful in identifying the pin key of the code and hence inserting the same in the main list also. It helps the user sort the list according to his own priorities.

**Syntax for Python takewhile()**

itertools.takewhile(predicate, sequence)

**Code:**

from itertools import * THISISTECH = takewhile(lambda i: i < [3, 12]) for val in THISISTECH: print(val)

**Output:**

## Conclusion

In this article we’ve read what are itertools, how are they user-oriented functions and how can they be used in a code. Towards the end of the article, we’ve also read the various categories in which these tools can be efficiently used.