Enable Dark Mode! By: Shonima

# An Overview of Itertools in Python & Its Functions & Classes

## Technical Odoo 16

Itertools is a module in Python's standard library that provides various functions for creating and manipulating iterators. It offers a collection of tools for efficient iteration, combining, and operating on iterable (sequences, iterators, and generators).
Here are some commonly used functions and classes from the itertools module:
1. count(start=0, step=1): Generates an infinite iterator that returns consecutive integers starting from the start with a step of step.
from itertools import count
`# Create an iterator that counts from 5 with a step of 2counter = count(5, 2)# Print the first 5 numbersfor i in range(5):	print(next(counter))`
Output :
5
7
9
11
13
2. cycle(iterable): Creates an infinite iterator that repeats the elements of the iterable indefinitely.
from itertools import cycle
`colors = ['red', 'green', 'blue']color_cycle = cycle(colors)# Print the first 10 elements from the color cyclefor i in range(10):	print(next(color_cycle))`
Output:
red
green
blue
red
green
blue
red
green
blue
Red
In this example, we have a list of colors ['red', 'green', 'blue']. We create a cycle object called color_cycle using the cycle function and pass in the colors list as the argument. The color_cycle object is an iterator that will infinitely cycle over the elements of the colors list.
We then use a for loop and the next function to iterate over the color_cycle object and print the next color from the cycle. In this case, we print the first ten colors, and since the cycle is infinite, it will continue cycling through the colors as needed.
Note that if you don't limit the number of iterations, the color_cycle will keep cycling indefinitely. You can use a condition or itertools.islice to control the number of iterations if needed.
3.repeat(element, times=None): Returns an iterator that repeatedly returns the specified element either indefinitely or a specified number of times.
from itertools import repeat
`# Repeat the value 5 three timesrepeated_values = repeat(5, 3)# Print the repeated valuesfor value in repeated_values:    print(value)`
Output:
5
5
5
In this example, we use the repeat function to create an iterator called repeated_values. We pass in the value five as the first argument and the number 3 as the second argument. This means that the iterator will repeat the value 5 three times.
We then use a for loop to iterate over the repeated_values iterator and print each value. As a result, we get the value 5 printed three times.
If you don't specify the number of times to repeat, the repeat function will create an iterator that produces the same value indefinitely. In such cases, you may need to use a condition or itertools.islice to control the number of iterations.
4.chain(*iterables): Combines multiple iterables into a single iterator by chaining them together. It returns elements from the first iterable until it is exhausted, and then proceeds to the next iterable, and so on.
import itertools
`my_list_1 = [1, 2, 3]my_list_2 = [4, 5, 6]my_list_3 = [7, 8, 9]# Chain the three lists togetherchained_list = list(itertools.chain(my_list_1, my_list_2, my_list_3))# Print the chained listprint(chained_list)`
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In this example, we have three lists (my_list_1, my_list_2, and my_list_3) that contain different elements. We use the itertools.chain function to chain these lists together and create an iterator that produces all the elements from each list in sequence.
To obtain a list from the iterator, we convert it to a list using the list function and store it in the variable chained_list.
Finally, we print the chained_list, which contains all the elements from the three lists combined.
You can adapt this example to suit your specific use case in Odoo. For instance, you might have different lists or sequences of data that you want to concatenate within a method or process in your Odoo model. By using itertools.chain, you can easily merge them into a single iterable or list.
5.islice(iterable, start, stop[, step]): Returns an iterator that returns selected elements from the iterable between the start and stop indices, with an optional step size.
from itertools import islice
`my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]# Slice the list to get elements from index 2 to 6sliced_list = list(islice(my_list, 2, 7))# Print the sliced listprint(sliced_list)`
Output:
[3, 4, 5, 6, 7]
In this example, we have a list called my_list containing elements from 1 to 10. We use islice to slice the list and retrieve elements from index 2 to 6. The islice function takes the iterable as the first argument and the start and stop indices as the second and third arguments, respectively.
We then convert the sliced iterable to a list using the list function and store it in the variable sliced_list. Finally, we print the sliced_list, which contains the elements [3, 4, 5, 6, 7].
Please note that islice returns an iterator, so if you want to obtain a list, you need to convert it using the list function as shown in the example.
6.zip_longest(*iterables, fillvalue=None): Returns an iterator that aggregates elements from multiple iterables. It stops when the longest iterable is exhausted, and the missing values are filled with fillvalue.
from itertools import zip_longest
`my_list_1 = [1, 2, 3]my_list_2 = ['a', 'b']# Zip the lists together, filling missing values with Nonezipped_lists = zip_longest(my_list_1, my_list_2)# Print the zipped listsfor item in zipped_lists:    print(item)`
Output:
(1, 'a')
(2, 'b')
(3, None)
In this example, we have two lists (my_list_1 and my_list_2) with different lengths. We use the zip_longest function to zip the lists together, ensuring that all elements are accounted for. The missing values are filled with None by default.
We then use a for loop to iterate over the zipped_lists and print each item. As a result, we get tuples representing the corresponding elements from each list. In this case, the third tuple contains (3, None) since the second list doesn't have a corresponding element for the third position.
You can also specify a custom fill value by passing it as the fillvalue argument to zip_longest. For example:
`zipped_lists = zip_longest(my_list_1, my_list_2, fillvalue=0)`
This would fill any missing values with 0 instead of None.
Note that zip_longest returns an iterator. If you want to obtain a list, you can convert it using the list function.
7.combinations(iterable, r): Generates all possible combinations of r elements from the given iterable.
from itertools import combinations
`my_list = [1, 2, 3, 4]# Generate all combinations of length 2 from the listcombinations_list = list(combinations(my_list, 2))# Print the combinationsfor combination in combinations_list:	print(combination)`
Output:
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
In this example, we have a list called my_list containing elements from 1 to 4. We use the combinations function to generate all combinations of length 2 from the list. The combinations function takes the iterable as the first argument and the length of the combinations as the second argument.
We then convert the combinations iterable to a list using the list function and store it in the variable combinations_list. Finally, we use a for loop to iterate over the combinations_list and print each combination.
As a result, we get all the possible combinations of length 2 from the list, without repetitions.
Note that the order of the elements within each combination is in the same order as they appear in the original iterable. Additionally, if you want to generate combinations with repetitions, you can use the combinations_with_replacement function from itertools instead of combinations.
8.permutations(iterable, r=None): Generates all possible permutations of r elements from the given iterable.
from itertools import permutations
`my_list = [1, 2, 3]# Generate all permutations of length 2 from the listpermutations_list = list(permutations(my_list, 2))# Print the permutationsfor permutation in permutations_list:	print(permutation)`
Output:
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)
In this example, we have a list called my_list containing elements from 1 to 3. We use the permutations function to generate all permutations of length 2 from the list. The permutations function takes the iterable as the first argument and the length of the permutations as the second argument.
We then convert the permutations iterable to a list using the list function and store it in the variable permutations_list. Finally, we use a for loop to iterate over the permutations_list and print each permutation.
As a result, we get all the possible permutations of length 2 from the list, considering the order of elements.
Note that the order of the elements within each permutation matters. If you want to generate permutations that allow repetitions, you can use the product function from itertools instead of permutations.
9.product(*iterables, repeat=1): Generates the Cartesian product of the input iterables, which is equivalent to nested for-loops.
from itertools import product
`my_list_1 = [1, 2]my_list_2 = ['a', 'b']# Generate the Cartesian product of the two listsproduct_list = list(product(my_list_1, my_list_2))# Print the Cartesian productfor item in product_list:	print(item)`
Output:
(1, 'a')
(1, 'b')
(2, 'a')
(2, 'b')
In this example, we have two lists (my_list_1 and my_list_2) containing different elements. We use the product function to generate the Cartesian product of these two lists. The product function takes multiple iterables as arguments.
We then convert the Cartesian product iterable to a list using the list function and store it in the variable product_list. Finally, we use a for loop to iterate over the product_list and print each item.
As a result, we get all possible combinations of elements from the two lists, allowing repetitions. In this case, the Cartesian product consists of tuples where the first element is from my_list_1 and the second element is from my_list_2.
Note that the number of elements in the Cartesian product is equal to the product of the lengths of the input iterables.
10.groupby(iterable, key=None): Groups consecutive elements of the iterable based on a common key. Returns an iterator of tuples containing the key and a group iterator.
The syntax for groupby is as follows:
`itertools.groupby(iterable, key=None)`
Here's how it works:
* iterable is the input sequence or iterable that you want to group.
* key is an optional parameter that specifies a function to generate a key for each element. By default, it uses the element itself as the key.
The groupby function returns an iterator that produces pairs (key, group), where key is the common key value and group is an iterator containing all the consecutive elements from the input iterable that share that key.
Here's a simple example to illustrate the usage of groupby:
import itertools
`data = [1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4]groups = itertools.groupby(data)for key, group in groups:	print(f"Key: {key}, Group: {list(group)}")`
Output:
Key: 1, Group: [1, 1]
Key: 2, Group: [2, 2]
Key: 3, Group: [3, 3, 3]
Key: 4, Group: [4, 4, 4, 4]
In this example, the data list contains consecutive elements with repeated values. The groupby function groups these elements based on their values, and the resulting iterator produces pairs of (key, group) where each group contains consecutive elements with the same value.
Note that the input iterable needs to be sorted based on the grouping key for groupby to work correctly. If the input is not sorted, you can use the sorted function or sort the iterable beforehand to ensure the desired grouping behavior.
Additionally, it's important to note that the groupby function only groups consecutive elements with the same key. If you need to group non-consecutive elements or elements based on a more complex condition, you may need to preprocess or sort the iterable accordingly before using groupby.

If you need any assistance in odoo, we are online, please chat with us.

### Recent Posts

#### What are the Different HTTP Status Codes in Odoo 16 Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635 London

Cybrosys Limited
Alpha House,
100 Borough High Street, London,
SE1 1LB, United Kingdom Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Kochi, India - 682030. Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,