{"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-08-09T19:42:46","modified_gmt":"2026-08-09T18:42:46","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":"\n<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>\n\n\n<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>\n\n\n<div class=\"wp-block-group has-background has-global-padding is-layout-constrained wp-container-core-group-is-layout-7441ce17 wp-block-group-is-layout-constrained\" style=\"border-left-color:#ff5c43;border-left-width:4px;border-radius:12px;background-color:#fff5f2;margin-top:32px;margin-bottom:32px;padding-top:24px;padding-right:28px;padding-bottom:24px;padding-left:28px\">\n\n<p style=\"margin-top:0;margin-bottom:16px;font-size:clamp(14.642px, 0.915rem + ((1vw - 3.2px) * 0.575), 22px);font-style:normal;font-weight:600\">Related articles<\/p>\n\n\n<ul class=\"wp-block-list\" style=\"margin-top:0;margin-bottom:0;padding-left:20px\">\n<li><a href=\"https:\/\/liora.io\/en\/matplotlib-master-data-visualization-in-python\" rel=\"noopener\" target=\"_blank\">Matplotlib: Master Data Visualization in Python <\/a><\/li>\n<li><a href=\"https:\/\/liora.io\/en\/python-all-you-need-to-know\" rel=\"noopener\" target=\"_blank\">Python Crash Course: Get started <\/a><\/li>\n<li><a href=\"https:\/\/liora.io\/en\/machine-learning-python-where-to-start\" rel=\"noopener\" target=\"_blank\">Mastering Machine Learning in Python: Data-Driven Success <\/a><\/li>\n<li><a href=\"https:\/\/liora.io\/en\/python-programming-for-beginners-episode-3\" rel=\"noopener\" target=\"_blank\">Python Programming for Beginners ,  Episode 3<\/a><\/li>\n<li><a href=\"https:\/\/liora.io\/en\/django-all-about-the-python-web-development-framework\" rel=\"noopener\" target=\"_blank\">Django: All about the Python web development framework<\/a><\/li>\n<li><a href=\"https:\/\/liora.io\/en\/numpy-the-python-library-in-data-science\" rel=\"noopener\" target=\"_blank\">NumPy : the most used Python library in Data Science<\/a><\/li>\n<\/ul>\n\n<\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"the-for-loop\">The &#8220;for&#8221; loop<\/h2>\n\n\n<p>The <strong>for<\/strong> 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 ,  an immutable collection of elements ,  string) or other iterable objects, and execute a block of code for each element.<\/p>\n\n\n<h3 class=\"wp-block-heading\" id=\"1-basic-concept\">1. Basic concept<\/h3>\n\n\n<p>Its syntax is simple and intuitive:<\/p>\n\n\n<pre class=\"wp-block-code\"><code>\n\t\t\t\t\tfor element in sequence:\n    # block of code to execute for each element\n\t\t\t\t<\/code><\/pre>\n\n\n<p>For example, to display each letter of a string :<\/p>\n\n\n<pre class=\"wp-block-code\"><code>\n\t\t\t\t\tfor letter in \"Python\":\n    print(letter)\n\t\t\t\t<\/code><\/pre>\n\n\n<h3 class=\"wp-block-heading\" id=\"2-use-with-the-range-function\">2. Use with the range() function<\/h3>\n\n\n<p>One of the most commonly used functions with the <strong>for<\/strong> loop is <strong>range ()<\/strong>. It generates a sequence of numbers, which is useful for executing a loop a defined number of times.<\/p>\n\n\n<pre class=\"wp-block-code\"><code>\n\t\t\t\t\tfor i in range(5):\n    print(i)\n\t\t\t\t<\/code><\/pre>\n\n\n<p>The example above displays numbers from 0 to 4 (<strong>range(5)<\/strong> generates a sequence that starts at 0 and stops before 5).<\/p>\n\n\n<h3 class=\"wp-block-heading\" id=\"3-browse-lists\">3. Browse lists<\/h3>\n\n\n<p>Lists are among the objects most commonly used with the <strong>for<\/strong>loop. To display the names in a list, for example:<\/p>\n\n\n<pre class=\"wp-block-code\"><code>\n\t\t\t\t\tnoms = [\"Alice\", \"Bob\", \"Charlie\"]\nfor nom in noms:\n    print(nom)\n\t\t\t\t<\/code><\/pre>\n\n\n<h3 class=\"wp-block-heading\" id=\"4-nested-loops\">4. Nested loops<\/h3>\n\n\n<p>It&#8217;s possible to use a <strong>for<\/strong> loop inside another <strong>for<\/strong> loop. For example, to display a multiplication table:<\/p>\n\n\n<pre class=\"wp-block-code\"><code>\n\t\t\t\t\tfor i in range(1, 4):\n    for j in range(1, 4):\n        print(f\"{i} x {j} = {i*j}\")\n\t\t\t\t<\/code><\/pre>\n\n\n<p>Nested loops can be powerful, but should be used with caution to avoid excessive complexity.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex is-content-justification-center wp-container-core-buttons-is-layout-5ee10de4\" style=\"margin-top:32px;margin-bottom:32px\"><div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"\/en\/courses\/data-ai\/data-scientist\">Explore our Data Scientist course<\/a><\/div><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"the-while-loop\">The &#8220;while&#8221; loop<\/h2>\n\n\n<p>In contrast to the <strong>for<\/strong> loop, which traverses a sequence of elements, the <strong>while<\/strong> 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.<\/p>\n\n\n<h3 class=\"wp-block-heading\" id=\"1-basic-concept-2\">1. Basic concept<\/h3>\n\n\n<p>Its syntax is as follows:<\/p>\n\n\n<pre class=\"wp-block-code\"><code>\n\t\t\t\t\twhile condition:\n    # block of code to be executed as long as the condition is true\n\t\t\t\t<\/code><\/pre>\n\n\n<p>For example, to display numbers from 0 to 4 :<\/p>\n\n\n<pre class=\"wp-block-code\"><code>\n\t\t\t\t\ti = 0\nwhile i &lt; 5:\n    print(i)\n    i += 1\n\t\t\t\t<\/code><\/pre>\n\n\n<p>Note the importance of incrementing variable i at each iteration to avoid an endless loop.<\/p>\n\n\n<h3 class=\"wp-block-heading\" id=\"2-precautions\">2. Precautions<\/h3>\n\n\n<p>The 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:<\/p>\n\n\n<ul class=\"wp-block-list\">\n<li aria-level=\"1\">Make sure you have a condition that will become false at some point.<\/li>\n<li aria-level=\"1\">Check conditions and control variables regularly during the development phase.<\/li>\n<\/ul>\n\n\n<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>\n\n\n<pre class=\"wp-block-code\"><code>\n\t\t\t\t\tlimit = 100\nvalue = 1\nwhile value &lt; 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\n\t\t\t\t<\/code><\/pre>\n\n\n<p>In the above example, the condition <strong>value <\/strong><strong>&lt;<\/strong><strong>limit<\/strong> will always be true since the value is never modified.<\/p>\n\n\n<h3 class=\"wp-block-heading\" id=\"3-practical-use\">3. Practical use<\/h3>\n\n\n<p>The <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:<\/p>\n\n\n<pre class=\"wp-block-code\"><code>\n\t\t\t\t\tpassword = \"secret\ninput = \"\"\nwhile input != password:\n    input = input(\"Enter password: \")\nprint(\"Access granted.\")\n\t\t\t\t<\/code><\/pre>\n\n\n<p>The <strong>while<\/strong> loop is a valuable tool. Although it offers great flexibility, it is crucial to use it with care and discernment.<\/p>\n\n\n<h2 class=\"wp-block-heading\" id=\"flow-control-in-loops\">Flow control in loops<\/h2>\n\n\n<p>Python offers several tools for managing the flow of execution within loops, allowing greater flexibility.<\/p>\n\n\n<h3 class=\"wp-block-heading\" id=\"1-break-and-continue-instructions\">1. Break and continue instructions<\/h3>\n\n\n<ul class=\"wp-block-list\">\n<li><strong>break<\/strong><strong> : <\/strong>Exit the current loop immediately. Execution resumes at the code block following the loop.<\/li>\n<\/ul>\n\n\n<p>Example: Find the first number divisible by 7 in a list.<\/p>\n\n\n<pre class=\"wp-block-code\"><code>\n\t\t\t\t\tnumbers = [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\n\t\t\t\t<\/code><\/pre>\n\n\n<ul class=\"wp-block-list\">\n<li><strong>continue<\/strong> : Interrupts the current iteration and proceeds to the next, without exiting the loop.<\/li>\n<\/ul>\n\n\n<p><i>Example: Display all numbers except those divisible by 3.<\/i><\/p>\n\n\n<pre class=\"wp-block-code\"><code>\n\t\t\t\t\tfor i in range(10):\n    if i % 3 == 0:\n        continue\n    print(i)\n\t\t\t\t<\/code><\/pre>\n\n\n<h3 class=\"wp-block-heading\" id=\"2-the-else-clause-with-loops\">2. The else clause with loops<\/h3>\n\n\n<p>Little known, the <strong>else<\/strong> clause can be used with the <strong>for<\/strong> and <strong>while<\/strong> 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.<\/p>\n\n\n<pre class=\"wp-block-code\"><code>\n\t\t\t\t\tn = 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.\")\n\t\t\t\t<\/code><\/pre>\n\n\n<p>In this example, if no divisor is found for <strong><i>n<\/i><\/strong>, the <strong>else<\/strong> clause will be executed.<\/p>\n\n\n<h2 class=\"wp-block-heading\" id=\"tips-and-best-practices\">Tips and best practices<\/h2>\n\n\n<figure class=\"wp-block-image aligncenter size-full is-resized\" style=\"width:512px;max-width:100%;margin-top:32px;margin-right:auto;margin-bottom:32px;margin-left:auto\"><img alt=\"Illustration for Tips and best practices\" decoding=\"async\" height=\"512\" loading=\"lazy\" src=\"https:\/\/liora.io\/app\/uploads\/2023\/10\/image3-6.png\" style=\"width:512px;max-width:100%;height:auto\" width=\"512\"\/><\/figure>\n\n\n<h2 class=\"wp-block-heading\" id=\"infinite-loops\">Infinite loops<\/h2>\n\n\n<p>Infinite loops, especially with <strong>while<\/strong>, are a frequent pitfall. Make sure you have a clear stop condition.<\/p>\n\n\n<figure class=\"wp-block-image aligncenter size-full is-resized\" style=\"width:512px;max-width:100%;margin-top:32px;margin-right:auto;margin-bottom:32px;margin-left:auto\"><img alt=\"Illustration for Infinite loops\" decoding=\"async\" height=\"512\" loading=\"lazy\" src=\"https:\/\/liora.io\/app\/uploads\/2023\/10\/image2-7.png\" style=\"width:512px;max-width:100%;height:auto\" width=\"512\"\/><\/figure>\n\n\n<h2 class=\"wp-block-heading\" id=\"list-comprehension\">List comprehension<\/h2>\n\n\n<p>A Python feature to create lists in a concise and elegant way. Instead of a loop<strong>for<\/strong>, use list comprehension..<\/p>\n\n\n<p><i>Example <\/i>: Create a list of the squares of the numbers from 0 to 9.<\/p>\n\n\n<pre class=\"wp-block-code\"><code>squares = [x**2 for x in range(10)]<\/code><\/pre>\n\n\n<figure class=\"wp-block-image aligncenter size-full is-resized\" style=\"width:256px;max-width:100%;margin-top:32px;margin-right:auto;margin-bottom:32px;margin-left:auto\"><img alt=\"Illustration for List comprehension\" decoding=\"async\" height=\"256\" loading=\"lazy\" src=\"https:\/\/liora.io\/app\/uploads\/2023\/10\/image1-10.png\" style=\"width:256px;max-width:100%;height:auto\" width=\"256\"\/><\/figure>\n\n\n<h2 class=\"wp-block-heading\" id=\"limit-the-depth-of-interlocking-loops\">Limit the depth of interlocking loops<\/h2>\n\n\n<p>Avoid too many overlapping loops, as they complicate legibility. For more than three levels, consider other solutions.<\/p>\n\n\n<figure class=\"wp-block-image aligncenter size-full is-resized\" style=\"width:512px;max-width:100%;margin-top:32px;margin-right:auto;margin-bottom:32px;margin-left:auto\"><img alt=\"Illustration for Limit the depth of interlocking loops\" decoding=\"async\" height=\"512\" loading=\"lazy\" src=\"https:\/\/liora.io\/app\/uploads\/2023\/10\/image4-8.png\" style=\"width:512px;max-width:100%;height:auto\" width=\"512\"\/><\/figure>\n\n\n<h2 class=\"wp-block-heading\" id=\"document\">Document<\/h2>\n\n\n<p>A comment clarifies the purpose of the loop, especially for complex loops.<\/p>\n\n\n<figure class=\"wp-block-image aligncenter size-full is-resized\" style=\"width:512px;max-width:100%;margin-top:32px;margin-right:auto;margin-bottom:32px;margin-left:auto\"><img alt=\"Illustration for Document\" decoding=\"async\" height=\"512\" loading=\"lazy\" src=\"https:\/\/liora.io\/app\/uploads\/2023\/10\/image5-8.png\" style=\"width:512px;max-width:100%;height:auto\" width=\"512\"\/><\/figure>\n\n\n<h2 class=\"wp-block-heading\" id=\"beware-of-complexity\">Beware of complexity<\/h2>\n\n\n<p>Structure your loops wisely to optimize performance. Avoid costly in-loop operations.<\/p>\n\n\n<h2 class=\"wp-block-heading\" id=\"conclusion\">Conclusion<\/h2>\n\n\n<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>\n\n\n<div class=\"wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex is-content-justification-center wp-container-core-buttons-is-layout-5ee10de4\" style=\"margin-top:32px;margin-bottom:32px\"><div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/liora.io\/en\/courses\/data-ai\/data-analyst\">Book an appointment<\/a><\/div><\/div>\n\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":4,"href":"https:\/\/liora.io\/en\/wp-json\/wp\/v2\/posts\/182855\/revisions"}],"predecessor-version":[{"id":211065,"href":"https:\/\/liora.io\/en\/wp-json\/wp\/v2\/posts\/182855\/revisions\/211065"}],"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}]}}