{"id":5731,"date":"2020-05-11T15:56:50","date_gmt":"2020-05-11T15:56:50","guid":{"rendered":"https:\/\/www.askpython.com\/?p=5731"},"modified":"2022-08-06T13:12:16","modified_gmt":"2022-08-06T13:12:16","slug":"python-itertools-module","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/python-itertools-module","title":{"rendered":"A Guide to using Python Itertools Module"},"content":{"rendered":"\n<p>In this article, we&#8217;ll take a look at using the Python itertools Module.<\/p>\n\n\n\n<p>This module is very useful if you want to create different types of iterators suitable for various tasks.<\/p>\n\n\n\n<p>If you&#8217;re able to learn some of the methods of this module, this could be a very useful addition to your toolbox! Let&#8217;s get started now, by going through some useful methods.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Python Itertools &#8211; Useful Methods<\/h2>\n\n\n\n<p>In this section, we&#8217;ll look at some useful methods which generate iterators.<\/p>\n\n\n\n<p>To use this module, we must first import it. This is already available in the standard library, so it&#8217;s pre-installed!<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport itertools\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Using Python itertools.chain() to chain iterables together<\/h3>\n\n\n\n<p>The Python <code>itertools.chain()<\/code> method generates an iterator from multiple iterables.<\/p>\n\n\n\n<p>This simply chains all the iterables together into one sequence and returns a single iterator to that combined sequence.<\/p>\n\n\n\n<p>The syntax for this method is as follows<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\niterator = itertools.chain(*sequence)\n<\/pre><\/div>\n\n\n<p>Let&#8217;s look at a simple example, to understand this.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport itertools\n\nlist1 = &#x5B;&#039;hello&#039;, &#039;from&#039;, &#039;AskPython&#039;]\nlist2 = &#x5B;10, 20, 30, 40, 50]\ndict1 = {&#039;site&#039;: &#039;AskPython&#039;, &#039;url&#039;: &#039;https:\/\/askpython.com&#039;}\n\n# We can combine lists and dicts (iterables) into a single chain\nfor item in itertools.chain(list1, list2, dict1):\n    print(item)\n<\/pre><\/div>\n\n\n<p>Here, we use the iterator directly, by iterating through it, using <code>for item in ...<\/code><\/p>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nhello\nfrom\nAskPython\n10\n20\n30\n40\n50\nsite\nurl\n<\/pre><\/div>\n\n\n<p>Here, although we get the contents of our lists correctly, the dictionary values are not displayed.<\/p>\n\n\n\n<p>To fix this, we could use <code>dict.items()<\/code> to get a tuple of <code>(key, value)<\/code> pairs.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport itertools\n\nlist1 = &#x5B;&#039;hello&#039;, &#039;from&#039;, &#039;AskPython&#039;]\nlist2 = &#x5B;10, 20, 30, 40, 50]\ndict1 = {&#039;site&#039;: &#039;AskPython&#039;, &#039;url&#039;: &#039;https:\/\/askpython.com&#039;}\n\n# We can combine lists and dicts (iterables) into a single chain\nfor item in itertools.chain(list1, list2, dict1.items()):\n    print(item)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nhello\nfrom\nAskPython\n10\n20\n30\n40\n50\n(&#039;site&#039;, &#039;AskPython&#039;)\n(&#039;url&#039;, &#039;https:\/\/askpython.com&#039;)\n<\/pre><\/div>\n\n\n<p>Indeed, we now have the values printed as well, using <code>dict1.items()<\/code> as the iterable!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Using Python itertools.count() to generate a counter-based sequence<\/h3>\n\n\n\n<p>We can use the function Python <code>itertools.count()<\/code> to make iterators corresponding to a count.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\niterator = itertools.count(start=0, step=1)\n<\/pre><\/div>\n\n\n<p>Here, this is an iterator which keeps counting indefinitely, from 0 onward.<\/p>\n\n\n\n<p>This keeps increasing the count by <code>step=1<\/code>. We can also set this to a decimal\/negative number.<\/p>\n\n\n\n<p>For example, if you want to prove that you have an infinite loop, you can run the below snippet, but it is <strong>NOT <\/strong>recommended.<\/p>\n\n\n\n<p>Just make sure that you can understand that <code>itertools.count()<\/code> counts infinitely.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfor num in itertools.count(start=0, step=1):\n    # Infinite loop!\n    print(num)\n<\/pre><\/div>\n\n\n<p>Now, while you may not find the use of this function immediately obvious, you can combine it with other functions such as the <a href=\"https:\/\/www.askpython.com\/python\/built-in-methods\/python-zip-function\" class=\"rank-math-link\">zip method <\/a>to construct sequences.<\/p>\n\n\n\n<p>Consider the below example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport itertools\nnumbers = &#x5B;100, 200, 300, 400]\n\ndata = list(zip(itertools.count(0, 10), numbers))\n\nprint(data)\n<\/pre><\/div>\n\n\n<p>Here, you can now see the power of iterators! Since iterators produce outputs only on demand, we can <code>zip()<\/code> it with another finite iterable, such as a list!<\/p>\n\n\n\n<p>Now, this is used to construct indices for items in the list, as you can verify using the output!<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&#x5B;(0, 100), (10, 200), (20, 300), (30, 400)]\n<\/pre><\/div>\n\n\n<p>Now, if you want to have a subset of the iterator sequence using Python <code>itertools.count()<\/code>, you can also use <code>itertools.islice()<\/code> to construct only a slice of the iterator.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport itertools\n\nfor num in itertools.islice(itertools.count(start=0, step=10), 4):\n    print(num)\n\nfor num in itertools.islice(itertools.count(), 0, 50, 10):\n    print(num)\n<\/pre><\/div>\n\n\n<p>Output<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n0\n10\n20\n30\n0\n10\n20\n30\n40\n<\/pre><\/div>\n\n\n<p>As you can observe, both the sequences are identical. This shows that you can have multiple approaches to generate sequences!<\/p>\n\n\n\n<p>Use the method which you see fit, based on the problem to solve!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using itertools.repeat() to repeat a value<\/h2>\n\n\n\n<p>Suppose you want to repeat a particular value, you can construct an iterator for the repeated value using <code>itertools.repeat(value)<\/code>.<\/p>\n\n\n\n<p>For example, if you want to construct a sequence of the form <code>(i, 5)<\/code>, where i ranges from 0 to 10, you can use this function!<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport itertools\n\ndata = list(zip(range(10), itertools.repeat(5)))\nprint(data)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n&#x5B;(0, 5),\n (1, 5),\n (2, 5),\n (3, 5),\n (4, 5),\n (5, 5),\n (6, 5),\n (7, 5),\n (8, 5),\n (9, 5)]\n<\/pre><\/div>\n\n\n<p>Indeed, we were able to make this sequence easily!<\/p>\n\n\n\n<p>Another example which this function is useful is if you&#8217;re trying to construct squares using <a href=\"https:\/\/www.askpython.com\/python\/built-in-methods\/map-method-in-python\" class=\"rank-math-link\">map() in Python<\/a>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nsquares = list(map(pow, range(10), itertools.repeat(2)))\nprint(squares)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n&#x5B;0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n<\/pre><\/div>\n\n\n<p>See how easily we were able to construct it using <code>map()<\/code>?<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Using itertools.tee() to clone sequences<\/h3>\n\n\n\n<p>There is another useful function called <code>tee()<\/code>, which clones a sequence, and produces two sequences.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ncloned1, cloned2 = itertools.tee(original_sequence)\n<\/pre><\/div>\n\n\n<p>This is based on the Linux tee command, which clones its outputs.<\/p>\n\n\n\n<p>Here, when you clone a sequence using <code>tee()<\/code>, you cannot use the same iterator again. As a result, you must be very careful when using this function!<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport itertools\n\nsingle_iterator = itertools.islice(itertools.count(), 3)\ncloned1, cloned2 = itertools.tee(single_iterator)\n\nfor num in cloned1:\n    print(&#039;cloned1: {}&#039;.format(num))\nfor num in cloned2:\n    print(&#039;cloned2: {}&#039;.format(num))\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncloned1: 0\ncloned1: 1\ncloned1: 2\ncloned2: 0\ncloned2: 1\ncloned2: 2\n<\/pre><\/div>\n\n\n<p>Indeed, we could see two cloned sequences, having the same outputs!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Cycle through sequences using itertools.cycle()<\/h3>\n\n\n\n<p>The <code>itertools.cycle()<\/code> function provides an iterator that we can cycle through indefinitely!<\/p>\n\n\n\n<p>This is useful if you want to keep switching between states in your application.<\/p>\n\n\n\n<p>Consider two states of a bulb: &#8220;on&#8221; and &#8220;off&#8221;.<\/p>\n\n\n\n<p>You can construct an iterator which cycles through the two states whenever the switch is pressed!<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport itertools\n\n# Initially, bulb is switched off, so off is the first element in the list\nbulb_states = itertools.cycle(&#x5B;&quot;off&quot;, &quot;on&quot;])\n\nfor _ in range(5):\n    # Use next(iterator) to get the current state\n    curr_state = next(bulb_states)\n    print(f&quot;Bulb state currently {curr_state}&quot;)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nBulb state currently off\nBulb state currently on\nBulb state currently off\nBulb state currently on\nBulb state currently off\n<\/pre><\/div>\n\n\n<p>Indeed, as you can see, the bulb state keeps getting cycled between the two values &#8220;on&#8221; and &#8220;off&#8221;!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Filter items using takewhile() and dropwhile()<\/h3>\n\n\n\n<p>We can use the Python <code>itertools.takewhile()<\/code> function to filter sequence items as long as a condition is <code>True<\/code>. If the condition becomes <code>False<\/code>, it stops filtering.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\niterator = itertools.takewhile(condition, *sequence)\n<\/pre><\/div>\n\n\n<p>Here is a simple example, which filters numbers, as long as the number is positive.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport itertools\n\nsequence = itertools.takewhile(lambda x: x &gt; 0, &#x5B;1, 2, 3, -1, 10])\n\nfor item in sequence:\n    print(item)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n1\n2\n3\n<\/pre><\/div>\n\n\n<p>Here, the sequence stopped after 3, since the next element is -1.<\/p>\n\n\n\n<p>Similarly, the <code>itertools.dropwhile()<\/code> filters elements as long as a condition is <code>False<\/code> and returns all the elements after the first non-false value.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport itertools\n\ndata = itertools.dropwhile(lambda x: x &lt; 5, &#x5B;3, 12, 7, 1, -5])\nfor item in data:\n    print(item)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n12\n7\n1\n-5\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Construct combinations using combinations()<\/h3>\n\n\n\n<p>We can also construct combination sequences using Python <code>itertools.combinations()<\/code>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\niterator = itertools.combinations(*sequence, r)\n<\/pre><\/div>\n\n\n<p><strong>Here is a simple example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport itertools\nwords = &#x5B;&#039;hello&#039;, &#039;from&#039;, &#039;AskPython&#039;, &#039;how&#039;]\nresults = itertools.combinations(words, 2)\nfor item in results:\n    print(item)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n(&#039;hello&#039;, &#039;from&#039;)\n(&#039;hello&#039;, &#039;AskPython&#039;)\n(&#039;hello&#039;, &#039;how&#039;)\n(&#039;from&#039;, &#039;AskPython&#039;)\n(&#039;from&#039;, &#039;how&#039;)\n(&#039;AskPython&#039;, &#039;how&#039;)\n<\/pre><\/div>\n\n\n<p>If you want to have repetitions of consecutive elements in the combinations, you can use <code>combinations_with_replacement()<\/code>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nresults = itertools.combinations_with_replacement(words, 3)\n\nfor item in results:\n    print(item)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n(&#039;hello&#039;, &#039;hello&#039;, &#039;hello&#039;)\n(&#039;hello&#039;, &#039;hello&#039;, &#039;from&#039;)\n(&#039;hello&#039;, &#039;hello&#039;, &#039;AskPython&#039;)\n(&#039;hello&#039;, &#039;hello&#039;, &#039;how&#039;)\n(&#039;hello&#039;, &#039;from&#039;, &#039;from&#039;)\n(&#039;hello&#039;, &#039;from&#039;, &#039;AskPython&#039;)\n(&#039;hello&#039;, &#039;from&#039;, &#039;how&#039;)\n(&#039;hello&#039;, &#039;AskPython&#039;, &#039;AskPython&#039;)\n(&#039;hello&#039;, &#039;AskPython&#039;, &#039;how&#039;)\n(&#039;hello&#039;, &#039;how&#039;, &#039;how&#039;)\n(&#039;from&#039;, &#039;from&#039;, &#039;from&#039;)\n(&#039;from&#039;, &#039;from&#039;, &#039;AskPython&#039;)\n(&#039;from&#039;, &#039;from&#039;, &#039;how&#039;)\n(&#039;from&#039;, &#039;AskPython&#039;, &#039;AskPython&#039;)\n(&#039;from&#039;, &#039;AskPython&#039;, &#039;how&#039;)\n(&#039;from&#039;, &#039;how&#039;, &#039;how&#039;)\n(&#039;AskPython&#039;, &#039;AskPython&#039;, &#039;AskPython&#039;)\n(&#039;AskPython&#039;, &#039;AskPython&#039;, &#039;how&#039;)\n(&#039;AskPython&#039;, &#039;how&#039;, &#039;how&#039;)\n(&#039;how&#039;, &#039;how&#039;, &#039;how&#039;)\n<\/pre><\/div>\n\n\n<p>Similarly, you could list the permutations using <code>permutations()<\/code> and <code>permutations_with_replacement()<\/code>.<\/p>\n\n\n\n<p>That concludes some of the important functions of this module. For more functions, you can consult the <a class=\"rank-math-link rank-math-link\" href=\"https:\/\/docs.python.org\/3\/library\/itertools.html\" target=\"_blank\" rel=\"noopener\">official documentation<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this article, we looked at various functions in the Python <code>itertools<\/code> module. Depending on your problem, you could use one of multiple approaches, to construct sequences quickly!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/docs.python.org\/3\/library\/itertools.html\" class=\"rank-math-link\" target=\"_blank\" rel=\"noopener\">Itertools module<\/a> Documentation<\/li><li>JournalDev article on itertools module<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we&#8217;ll take a look at using the Python itertools Module. This module is very useful if you want to create different types of iterators suitable for various tasks. If you&#8217;re able to learn some of the methods of this module, this could be a very useful addition to your toolbox! Let&#8217;s get [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":5748,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-5731","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-modules"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/5731","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=5731"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/5731\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/5748"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=5731"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=5731"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=5731"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}