{"id":182855,"date":"2024-03-13T06:27:00","date_gmt":"2024-03-13T05:27:00","guid":{"rendered":"https:\/\/liora.io\/en\/?p=182855"},"modified":"2026-02-06T08:25:23","modified_gmt":"2026-02-06T07:25:23","slug":"python-loops-a-guide-for-efficient-iteration","status":"publish","type":"post","link":"https:\/\/liora.io\/en\/python-loops-a-guide-for-efficient-iteration","title":{"rendered":"Python loops: A Guide for Efficient Iteration"},"content":{"rendered":"<style>\n.elementor-heading-title{padding:0;margin:0;line-height:1}.elementor-widget-heading .elementor-heading-title[class*=elementor-size-]>a{color:inherit;font-size:inherit;line-height:inherit}.elementor-widget-heading .elementor-heading-title.elementor-size-small{font-size:15px}.elementor-widget-heading .elementor-heading-title.elementor-size-medium{font-size:19px}.elementor-widget-heading .elementor-heading-title.elementor-size-large{font-size:29px}.elementor-widget-heading .elementor-heading-title.elementor-size-xl{font-size:39px}.elementor-widget-heading .elementor-heading-title.elementor-size-xxl{font-size:59px}<\/style><p><strong>Automation and repetition are ubiquitous concepts in programming. Imagine having to perform the same action hundreds or even thousands of times. This would not only be tedious, but also a source of errors. Programming languages such as Python offer powerful tools for managing these repetitions: loops.<\/strong><\/p>\t\t\n\t\t<p>Whether you&#8217;re browsing a list of data, repeating an operation until a condition is met, or even generating sequences, loops are of paramount importance.<\/p><p>&nbsp;<\/p><p>?Related articles:<\/p><table dir=\"ltr\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\" data-sheets-root=\"1\"><colgroup><col width=\"656\"><\/colgroup><tbody><tr><td data-sheets-value=\"{&quot;1&quot;:2,&quot;2&quot;:&quot;Matplotlib: Master Data Visualization in Python &quot;}\" data-sheets-hyperlink=\"https:\/\/liora.io\/en\/matplotlib-master-data-visualization-in-python\"><a href=\"https:\/\/liora.io\/en\/matplotlib-master-data-visualization-in-python\" target=\"_blank\" rel=\"noopener\">Matplotlib: Master Data Visualization in Python <\/a><\/td><\/tr><tr><td data-sheets-value=\"{&quot;1&quot;:2,&quot;2&quot;:&quot;Python Crash Course: Get started &quot;}\" data-sheets-hyperlink=\"https:\/\/liora.io\/en\/python-all-you-need-to-know\"><a href=\"https:\/\/liora.io\/en\/python-all-you-need-to-know\" target=\"_blank\" rel=\"noopener\">Python Crash Course: Get started <\/a><\/td><\/tr><tr><td data-sheets-value=\"{&quot;1&quot;:2,&quot;2&quot;:&quot;Mastering Machine Learning in Python: Data-Driven Success &quot;}\" data-sheets-hyperlink=\"https:\/\/liora.io\/en\/machine-learning-python-where-to-start\"><a href=\"https:\/\/liora.io\/en\/machine-learning-python-where-to-start\" target=\"_blank\" rel=\"noopener\">Mastering Machine Learning in Python: Data-Driven Success <\/a><\/td><\/tr><tr><td data-sheets-value=\"{&quot;1&quot;:2,&quot;2&quot;:&quot;Python Programming for Beginners - Episode 3&quot;}\" data-sheets-hyperlink=\"https:\/\/liora.io\/en\/python-programming-for-beginners-episode-3\"><a href=\"https:\/\/liora.io\/en\/python-programming-for-beginners-episode-3\" target=\"_blank\" rel=\"noopener\">Python Programming for Beginners &#8211; Episode 3<\/a><\/td><\/tr><tr><td data-sheets-value=\"{&quot;1&quot;:2,&quot;2&quot;:&quot;Django: All about the Python web development framework&quot;}\" data-sheets-hyperlink=\"https:\/\/liora.io\/en\/django-all-about-the-python-web-development-framework\"><a href=\"https:\/\/liora.io\/en\/django-all-about-the-python-web-development-framework\" target=\"_blank\" rel=\"noopener\">Django: All about the Python web development framework<\/a><\/td><\/tr><tr><td data-sheets-value=\"{&quot;1&quot;:2,&quot;2&quot;:&quot;NumPy : the most used Python library in Data Science&quot;}\" data-sheets-hyperlink=\"https:\/\/liora.io\/en\/numpy-the-python-library-in-data-science\"><a href=\"https:\/\/liora.io\/en\/numpy-the-python-library-in-data-science\" target=\"_blank\" rel=\"noopener\">NumPy : the most used Python library in Data Science<\/a><\/td><\/tr><\/tbody><\/table>\t\t\n\t\t\t<h3>The &#8220;for&#8221; loop<\/h3>\t\t\n\t\tThe <b>for<\/b> loop is one of the most frequently used control structures in Python. It allows you to step through elements of a sequence (such as a list, tuple &#8211; an immutable collection of elements &#8211; string) or other iterable objects, and execute a block of code for each element.\t\t\n\t\t\t<h4>1. Basic concept<\/h4>\t\t\n\t\t<p>Its syntax is simple and intuitive:<\/p>\t\t\n\t\t\t<pre data-line=\"\">\t\t\t\t<code readonly=\"true\">\n\t\t\t\t\t<xmp>for element in sequence:\n    # block of code to execute for each element<\/xmp>\n\t\t\t\t<\/code>\n\t\t\t<\/pre>\n\t\t<p>For example, to display each letter of a string :<\/p>\t\t\n\t\t\t<pre data-line=\"\">\t\t\t\t<code readonly=\"true\">\n\t\t\t\t\t<xmp>for letter in \"Python\":\n    print(letter)<\/xmp>\n\t\t\t\t<\/code>\n\t\t\t<\/pre>\n\t\t\t<h4>2. Use with the range() function<\/h4>\t\t\n\t\tOne of the most commonly used functions with the <b>for<\/b> loop is <strong>range ()<\/strong>. It generates a sequence of numbers, which is useful for executing a loop a defined number of times.\t\t\n\t\t\t<pre data-line=\"\">\t\t\t\t<code readonly=\"true\">\n\t\t\t\t\t<xmp>for i in range(5):\n    print(i)<\/xmp>\n\t\t\t\t<\/code>\n\t\t\t<\/pre>\n\t\tThe example above displays numbers from 0 to 4 (<strong>range(5)<\/strong> generates a sequence that starts at 0 and stops before 5).\t\t\n\t\t\t<h4>3. Browse lists<\/h4>\t\t\n\t\tLists are among the objects most commonly used with the <b>for<\/b>loop. To display the names in a list, for example:\t\t\n\t\t\t<pre data-line=\"\">\t\t\t\t<code readonly=\"true\">\n\t\t\t\t\t<xmp>noms = [\"Alice\", \"Bob\", \"Charlie\"]\nfor nom in noms:\n    print(nom)<\/xmp>\n\t\t\t\t<\/code>\n\t\t\t<\/pre>\n\t\t\t<h4>4. Nested loops<\/h4>\t\t\n\t\tIt&#8217;s possible to use a <b>for<\/b> loop inside another <b>for<\/b> loop. For example, to display a multiplication table:\t\t\n\t\t\t<pre data-line=\"\">\t\t\t\t<code readonly=\"true\">\n\t\t\t\t\t<xmp>for i in range(1, 4):\n    for j in range(1, 4):\n        print(f\"{i} x {j} = {i*j}\")<\/xmp>\n\t\t\t\t<\/code>\n\t\t\t<\/pre>\n\t\t<p>Nested loops can be powerful, but should be used with caution to avoid excessive complexity.<\/p>\t\t\n\t\t\t<h3>The &#8220;while&#8221; loop<\/h3>\t\t\n\t\tIn contrast to the <b>for<\/b> loop, which traverses a sequence of elements, the <b>while<\/b> loop executes a block of code as long as a given condition is true. It offers additional flexibility, but also requires careful attention to avoid infinite loops.\t\t\n\t\t\t<h4>1. Basic concept<\/h4>\t\t\n\t\t<p>Its syntax is as follows:<\/p>\t\t\n\t\t\t<pre data-line=\"\">\t\t\t\t<code readonly=\"true\">\n\t\t\t\t\t<xmp>while condition:\n    # block of code to be executed as long as the condition is true<\/xmp>\n\t\t\t\t<\/code>\n\t\t\t<\/pre>\n\t\t<p>For example, to display numbers from 0 to 4 :<\/p>\t\t\n\t\t\t<pre data-line=\"\">\t\t\t\t<code readonly=\"true\">\n\t\t\t\t\t<xmp>i = 0\nwhile i < 5:\n    print(i)\n    i += 1<\/xmp>\n\t\t\t\t<\/code>\n\t\t\t<\/pre>\n\t\t<p>Note the importance of incrementing variable i at each iteration to avoid an endless loop.<\/p>\t\t\n\t\t\t<h4>2. Precautions<\/h4>\t\t\n\t\tThe main danger with the while loop is the risk of creating an infinite loop, where the block of code executes indefinitely because the condition always remains true. \nTo avoid this:\n<ul>\n \t<li style=\"font-weight: 400;\" aria-level=\"1\">Make sure you have a condition that will become false at some point.<\/li>\n \t<li style=\"font-weight: 400;\" aria-level=\"1\">Check conditions and control variables regularly during the development phase.<\/li>\n<\/ul><p>Let&#8217;s take an example of an infinite loop. Suppose we want to double the value of a variable until it reaches (or exceeds) a certain threshold.<\/p>\t\t\n\t\t\t<pre data-line=\"\">\t\t\t\t<code readonly=\"true\">\n\t\t\t\t\t<xmp>limit = 100\nvalue = 1\nwhile value < limit:\n    print(value)\n    # Forgot to increment or modify value\n   # Instead of doubling the value as planned, we forgot this step\n    # value *= 2<\/xmp>\n\t\t\t\t<\/code>\n\t\t\t<\/pre>\n\t\tIn the above example, the condition <strong>value <\/strong><b>&lt;<\/b> <strong>limit<\/strong> will always be true since the value is never modified.\t\t\n\t\t\t<h4>3. Practical use<\/h4>\t\t\n\t\tThe <strong>while<\/strong> loop is particularly useful when the number of iterations is not known in advance. For example, to ask the user to enter a correct password:\t\t\n\t\t\t<pre data-line=\"\">\t\t\t\t<code readonly=\"true\">\n\t\t\t\t\t<xmp>password = \"secret\ninput = \"\"\nwhile input != password:\n    input = input(\"Enter password: \")\nprint(\"Access granted.\")<\/xmp>\n\t\t\t\t<\/code>\n\t\t\t<\/pre>\n\t\tThe <b>while<\/b> loop is a valuable tool. Although it offers great flexibility, it is crucial to use it with care and discernment.\t\t\n\t\t\t<h3>Flow control in loops<\/h3>\t\t\n\t\t<p>Python offers several tools for managing the flow of execution within loops, allowing greater flexibility.<\/p>\t\t\n\t\t\t<h4>1. Break and continue instructions<\/h4>\t\t\n\t\t<ul>\n \t<li><b>break<\/b><b> : <\/b>Exit the current loop immediately. Execution resumes at the code block following the loop.<\/li>\n<\/ul><p>Example: Find the first number divisible by 7 in a list.<\/p>\t\t\n\t\t\t<pre data-line=\"\">\t\t\t\t<code readonly=\"true\">\n\t\t\t\t\t<xmp>numbers = [3, 5, 8, 12, 14, 18]\nfor n in numbers:\n    if n % 7 == 0:\n        print(f \"The first number divisible by 7 is {n}.\")\n        break<\/xmp>\n\t\t\t\t<\/code>\n\t\t\t<\/pre>\n\t\t<ul>\n \t<li><b>continue<\/b> : Interrupts the current iteration and proceeds to the next, without exiting the loop.<\/li>\n<\/ul><p><i>Example: Display all numbers except those divisible by 3.<\/i><\/p>\t\t\n\t\t\t<pre data-line=\"\">\t\t\t\t<code readonly=\"true\">\n\t\t\t\t\t<xmp>for i in range(10):\n    if i % 3 == 0:\n        continue\n    print(i)<\/xmp>\n\t\t\t\t<\/code>\n\t\t\t<\/pre>\n\t\t\t<h4>2. The else clause with loops<\/h4>\t\t\n\t\tLittle known, the <b>else<\/b> clause can be used with the <b>for<\/b> and <b>while<\/b> loops. It is executed when the loop ends normally (i.e. without being interrupted by a break).\n<i>Example <\/i>: Check if a number is prime.\t\t\n\t\t\t<pre data-line=\"\">\t\t\t\t<code readonly=\"true\">\n\t\t\t\t\t<xmp>n = 17\nfor i in range(2, n):\n    if n % i == 0:\n        print(f\"{n} is not a prime number.\")\n        break\nelse:\n    print(f\"{n} is a prime number.\")<\/xmp>\n\t\t\t\t<\/code>\n\t\t\t<\/pre>\n\t\tIn this example, if no divisor is found for <b><i>n<\/i><\/b>, the <b>else<\/b> clause will be executed.\t\t\n\t\t\t<h3>Tips and best practices<\/h3>\t\t\n\t\t\t<style>\n.elementor-widget-image{text-align:center}.elementor-widget-image a{display:inline-block}.elementor-widget-image a img[src$=\".svg\"]{width:48px}.elementor-widget-image img{vertical-align:middle;display:inline-block}<\/style>\t\t\t\t\t\t\t\t\t\t\t\t<img decoding=\"async\" src=\"https:\/\/liora.io\/app\/uploads\/2023\/10\/image3-6.png\" title=\"\" alt=\"\" loading=\"lazy\">\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t<h3>Infinite loops<\/h3>\t\t\n\t\tInfinite loops, especially with <b>while<\/b>, are a frequent pitfall. Make sure you have a clear stop condition.\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<img decoding=\"async\" src=\"https:\/\/liora.io\/app\/uploads\/2023\/10\/image2-7.png\" title=\"\" alt=\"\" loading=\"lazy\">\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t<h3>List comprehension<\/h3>\t\t\n\t\t<p>A Python feature to create lists in a concise and elegant way. Instead of a loop<b>for<\/b>, use list comprehension..<\/p><p><i>Example <\/i>: Create a list of the squares of the numbers from 0 to 9.<\/p><pre>squares <b>=<\/b> [x<b>**<\/b>2 <b>for<\/b> x <b>in<\/b> range(10)]<\/pre><p>&nbsp;<\/p>\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<img decoding=\"async\" src=\"https:\/\/liora.io\/app\/uploads\/2023\/10\/image1-10.png\" title=\"\" alt=\"\" loading=\"lazy\">\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t<h3>Limit the depth of interlocking loops<\/h3>\t\t\n\t\t<p>Avoid too many overlapping loops, as they complicate legibility. For more than three levels, consider other solutions.<\/p>\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<img decoding=\"async\" src=\"https:\/\/liora.io\/app\/uploads\/2023\/10\/image4-8.png\" title=\"\" alt=\"\" loading=\"lazy\">\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t<h3>Document<\/h3>\t\t\n\t\t<p>A comment clarifies the purpose of the loop, especially for complex loops.<\/p>\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<img decoding=\"async\" src=\"https:\/\/liora.io\/app\/uploads\/2023\/10\/image5-8.png\" title=\"\" alt=\"\" loading=\"lazy\">\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t<h3>Beware of complexity<\/h3>\t\t\n\t\t<p>Structure your loops wisely to optimize performance. Avoid costly in-loop operations.<\/p>\t\t\n\t\t\t<h3>Conclusion<\/h3>\t\t\n\t\t<p>Mastering loops is crucial for any Python developer. They offer the power to automate repetitive tasks, making code more efficient and concise. By following best practices and understanding the subtleties, you&#8217;ll optimize your programs while avoiding common pitfalls.<\/p>\t\t\n\t\t\t\n<div class=\"wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex is-content-justification-center\"><div class=\"wp-block-button \"><a class=\"wp-block-button__link wp-element-button \" href=\"\/en\/courses\/data-ai\/\">Book an appointment<\/a><\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Automation and repetition are ubiquitous concepts in programming. Imagine having to perform the same action hundreds or even thousands of times. This would not only be tedious, but also a source of errors. Programming languages such as Python offer powerful tools for managing these repetitions: loops. Whether you&#8217;re browsing a list of data, repeating an [&hellip;]<\/p>\n","protected":false},"author":76,"featured_media":182833,"comment_status":"open","ping_status":"open","sticky":false,"template":"elementor_theme","format":"standard","meta":{"_acf_changed":false,"editor_notices":[],"footnotes":""},"categories":[2434],"class_list":["post-182855","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cloud-dev"],"acf":[],"_links":{"self":[{"href":"https:\/\/liora.io\/en\/wp-json\/wp\/v2\/posts\/182855","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/liora.io\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/liora.io\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/liora.io\/en\/wp-json\/wp\/v2\/users\/76"}],"replies":[{"embeddable":true,"href":"https:\/\/liora.io\/en\/wp-json\/wp\/v2\/comments?post=182855"}],"version-history":[{"count":1,"href":"https:\/\/liora.io\/en\/wp-json\/wp\/v2\/posts\/182855\/revisions"}],"predecessor-version":[{"id":205997,"href":"https:\/\/liora.io\/en\/wp-json\/wp\/v2\/posts\/182855\/revisions\/205997"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/liora.io\/en\/wp-json\/wp\/v2\/media\/182833"}],"wp:attachment":[{"href":"https:\/\/liora.io\/en\/wp-json\/wp\/v2\/media?parent=182855"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/liora.io\/en\/wp-json\/wp\/v2\/categories?post=182855"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}