{"id":3623,"date":"2021-06-28T08:31:37","date_gmt":"2021-06-28T08:31:37","guid":{"rendered":"https:\/\/cloudxlab.com\/blog\/?p=3623"},"modified":"2021-08-23T06:02:12","modified_gmt":"2021-08-23T06:02:12","slug":"when-to-use-while-for-and-map-for-iterations-in-python","status":"publish","type":"post","link":"https:\/\/cloudxlab.com\/blog\/when-to-use-while-for-and-map-for-iterations-in-python\/","title":{"rendered":"When to use While, For, and Map for iterations in Python?"},"content":{"rendered":"\n<p>Python has a really sophisticated way of handling iterations. The only thing it does not have &#8220;GOTO Labels&#8221; which I think is good.<\/p>\n\n\n\n<p>Let us compare the three common ways of iterations in Python: While, For and Map by the way of an example. Imagine that you have a list of numbers and you would like to find the square of each number.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"\">nums = [1,2,3,5,10]\nresult = []\nfor num in nums:\n    result.append(num*num)\nprint(result)\n<\/code><\/pre>\n\n\n\n<p>It would print <code>[1, 4, 9, 25, 100]<\/code><\/p>\n\n\n\n<!--more-->\n\n\n\n<p>Alternative form of iteration using for is <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"\">nums = [1,2,3,5,10]\nresult = [num*num for num in nums]\nprint(result)<\/code><\/pre>\n\n\n\n<p>Now, let us try to use <code>while<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"\">nums = [1,2,3,5,10]\nresult = []\ni = 0\nwhile i &lt; len(nums):\n    num = nums[i]\n    result.append(num*num)\n    i += 1\n\nprint(result)<\/code><\/pre>\n\n\n\n<p>Look at both pieces of code. The <code>for<\/code> loop iterates over a list and <code>while<\/code> loop runs as long as the condition is true. So, if you forgot to increase <code>i<\/code>, the condition will remain false forever and <code>while<\/code> the loop will not end ever. That&#8217;s why <code>while<\/code> is called an indefinite loop. <\/p>\n\n\n\n<p>Not everything that can be achieved using <code>while<\/code> can be achieved using <code>for<\/code>. Everything that can be achieved using <code>for<\/code> can be achieved using <code>while<\/code>. <code>while<\/code> is way more powerful but with more power comes more risk.<\/p>\n\n\n\n<p>So, if your task can be performed using <code>for<\/code> don&#8217;t use <code>while<\/code>.<\/p>\n\n\n\n<p>Now, let&#8217;s take a look at <code>map<\/code>. The map is a very interesting way of running the independent operations on a list of things. I encountered the map paradigm around 18 years ago while doing grid computing using PERL programming language.<\/p>\n\n\n\n<p>Let&#8217;s take a look at the code to solve the same problem as above &#8211; squaring each number in a list.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"\">nums = [1,2,3,5,10]\ndef sq(x):\n    return x*x\n\nresult = map(sq, nums)\nprint(result)<\/code><\/pre>\n\n\n\n<p> Here notice that to the function we are passing our function <code>sq<\/code> and our array<code>nums<\/code>. The <code>map<\/code> function will run the <code>sq<\/code> function on each element of nums. Here it does not matter to us in what order will it run. Also, whether it uses different processors to run <code>sq<\/code> function on different parts of the list it would not impact our logic.<\/p>\n\n\n\n<p>The <code>map<\/code> function is way better to use over <code>for<\/code> loop but it has constraint. If the next value depends upon the previous computation, we would not be able to use map. So, <code>map<\/code> can only solve some problems that <code>for<\/code> can solve. And <code>for<\/code> can solve some problems that <code>while<\/code> can.<\/p>\n\n\n\n<p>Advantage of <code>map<\/code> is that your code will easily be parallelizable i.e. run on multiple computers or multiple processors if you are using <code>map<\/code>. The code with <code>for<\/code> loop and <code>while<\/code> loops we will have to rewrite the logic to make it parallelizable.<\/p>\n\n\n\n<p>Let us take the case of the Fibonacci series. Can we achieve the following using map()? I don&#8217;t think so. If you can, please put it in the comments.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"\">def fib(n):\n    result = []\n    first, second = 0, 1\n    result.extend([first, second])\n    for _ in range(n-1):\n        newnum = first + second\n        first, second = second, newnum\n        result.append(newnum)\n    print(result)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">&gt;&gt;&gt; fib(20)\n[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]         <\/pre>\n\n\n\n<p>This prints first twenty numbers of <code>Fibonacci<\/code> series.<\/p>\n\n\n\n<p>There are many examples which are very difficult to achieve using map. <\/p>\n\n\n\n<p>As a conclusion, your order of preference of usage should be:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"\"><strong>map &gt; for &gt; while<\/strong><\/code><\/pre>\n\n\n\n<p>Prefer <code>map<\/code> over &#8220;for&#8221; loop. Prefer <code>for<\/code> over &#8220;while&#8221; loop.<\/p>\n\n\n\n<p>I hope this discussion was useful to you. You can try it on <a href=\"https:\/\/cloudxlab.com\/lab\">CloudxLab<\/a> right away.<\/p>\n\n\n\n<p>Happy Learning!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python has a really sophisticated way of handling iterations. The only thing it does not have &#8220;GOTO Labels&#8221; which I think is good. Let us compare the three common ways of iterations in Python: While, For and Map by the way of an example. Imagine that you have a list of numbers and you would &hellip; <a href=\"https:\/\/cloudxlab.com\/blog\/when-to-use-while-for-and-map-for-iterations-in-python\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;When to use While, For, and Map for iterations in Python?&#8221;<\/span><\/a><\/p>\n","protected":false},"author":14,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[1],"tags":[138,137,136,135,94],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v16.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>When to use While, For, and Map for iterations in Python? | CloudxLab Blog<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/cloudxlab.com\/blog\/when-to-use-while-for-and-map-for-iterations-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"When to use While, For, and Map for iterations in Python? | CloudxLab Blog\" \/>\n<meta property=\"og:description\" content=\"Python has a really sophisticated way of handling iterations. The only thing it does not have &#8220;GOTO Labels&#8221; which I think is good. Let us compare the three common ways of iterations in Python: While, For and Map by the way of an example. Imagine that you have a list of numbers and you would &hellip; Continue reading &quot;When to use While, For, and Map for iterations in Python?&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/cloudxlab.com\/blog\/when-to-use-while-for-and-map-for-iterations-in-python\/\" \/>\n<meta property=\"og:site_name\" content=\"CloudxLab Blog\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/cloudxlab\" \/>\n<meta property=\"article:published_time\" content=\"2021-06-28T08:31:37+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-08-23T06:02:12+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@CloudxLab\" \/>\n<meta name=\"twitter:site\" content=\"@CloudxLab\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\">\n\t<meta name=\"twitter:data1\" content=\"3 minutes\">\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/#website\",\"url\":\"https:\/\/cloudxlab.com\/blog\/\",\"name\":\"CloudxLab Blog\",\"description\":\"Learn AI, Machine Learning, Deep Learning, Devops &amp; Big Data\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/cloudxlab.com\/blog\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/when-to-use-while-for-and-map-for-iterations-in-python\/#webpage\",\"url\":\"https:\/\/cloudxlab.com\/blog\/when-to-use-while-for-and-map-for-iterations-in-python\/\",\"name\":\"When to use While, For, and Map for iterations in Python? | CloudxLab Blog\",\"isPartOf\":{\"@id\":\"https:\/\/cloudxlab.com\/blog\/#website\"},\"datePublished\":\"2021-06-28T08:31:37+00:00\",\"dateModified\":\"2021-08-23T06:02:12+00:00\",\"author\":{\"@id\":\"https:\/\/cloudxlab.com\/blog\/#\/schema\/person\/4835f1b3d5000626cb15e9311d748e09\"},\"breadcrumb\":{\"@id\":\"https:\/\/cloudxlab.com\/blog\/when-to-use-while-for-and-map-for-iterations-in-python\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/cloudxlab.com\/blog\/when-to-use-while-for-and-map-for-iterations-in-python\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/when-to-use-while-for-and-map-for-iterations-in-python\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"item\":{\"@type\":\"WebPage\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/\",\"url\":\"https:\/\/cloudxlab.com\/blog\/\",\"name\":\"Home\"}},{\"@type\":\"ListItem\",\"position\":2,\"item\":{\"@id\":\"https:\/\/cloudxlab.com\/blog\/when-to-use-while-for-and-map-for-iterations-in-python\/#webpage\"}}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/#\/schema\/person\/4835f1b3d5000626cb15e9311d748e09\",\"name\":\"Sandeep Giri\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/1393214840cf7455bb4cba055cb30468?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/1393214840cf7455bb4cba055cb30468?s=96&d=mm&r=g\",\"caption\":\"Sandeep Giri\"},\"sameAs\":[\"https:\/\/cloudxlab.com\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","_links":{"self":[{"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/posts\/3623"}],"collection":[{"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/comments?post=3623"}],"version-history":[{"count":3,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/posts\/3623\/revisions"}],"predecessor-version":[{"id":3627,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/posts\/3623\/revisions\/3627"}],"wp:attachment":[{"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/media?parent=3623"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/categories?post=3623"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/tags?post=3623"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}