{"id":7216,"date":"2023-01-21T19:42:48","date_gmt":"2023-01-21T14:12:48","guid":{"rendered":"https:\/\/tutorpython.com\/?p=7216"},"modified":"2023-10-19T15:08:35","modified_gmt":"2023-10-19T09:38:35","slug":"for-loops-in-python","status":"publish","type":"post","link":"https:\/\/tutorpython.com\/for-loops-in-python","title":{"rendered":"For Loops in Python"},"content":{"rendered":"<p>In this article, we will learn about the different types of <a href=\"https:\/\/tutorpython.com\/tutorial\/for-loops-in-python\">for loops in Python<\/a> and how to use them effectively in our code. The loop is a fundamental concept in Python programming. And implementation of <strong>for loop<\/strong> is particularly powerful and versatile.<\/p>\n<p>We will start with the basic standard &#8220;for&#8221; loop which includes how to iterate over a sequence and use the range function. Next, we will see how the &#8220;for-each&#8221; loop differs from the standard for loop.<\/p>\n<h2>Types of For loop in Python<\/h2>\n<p>There are two main types of for loops in Python:<\/p>\n<ol>\n<li><strong>The standard for loop<\/strong>\u00a0iterates over a sequence of items (such as a list or string) and assigns each item to a variable on each iteration.<\/li>\n<li>And &#8220;<strong>for-each<\/strong>&#8221; loop, is implemented using the <strong>for<\/strong> keyword along with the <strong>in<\/strong> the keyword. This type of loop iterates over the elements of an iterable object (such as a list or dictionary), rather than using an index.<\/li>\n<\/ol>\n<h2>How can I write for loop in Python?<\/h2>\n<p>Below is the <a href=\"https:\/\/tutorpython.com\/tutorial\/python-syntax\" target=\"_blank\" rel=\"noopener\">syntax<\/a> for loop in Python with code examples and explanations.<\/p>\n<h3>Syntax of For loop in Python<\/h3>\n<p>The syntax for a standard <a href=\"https:\/\/realpython.com\/python-for-loop\/\" target=\"_blank\" rel=\"noopener\">for loop in Python<\/a> is as follows:<\/p>\n<pre><code class=\"language-python\">for variable in sequence:\r\n    # code to execute on each iteration\r\n<\/code><\/pre>\n<p>Here, the <strong>for <\/strong>in <a href=\"https:\/\/tutorpython.com\/tutorial\/keywords-identifiers-in-python\" target=\"_blank\" rel=\"noopener\">Python keyword<\/a> is used to initiate the loop. The <strong>variable<\/strong> is a placeholder that takes on the value of the next item in the <strong>sequence<\/strong> on each iteration. The <strong>sequence<\/strong> is the list, tuple, string, etc. that we want to iterate over. The code indented under the <strong>for<\/strong> statement is executed on each iteration.<\/p>\n<p>Example:<\/p>\n<pre><code class=\"language-python\">numbers = [1, 2, 3, 4, 5]\r\nfor num in numbers:\r\n    print(num)\r\n<\/code><\/pre>\n<p>The output for this code will be:<\/p>\n<pre>1\r\n2\r\n3\r\n4\r\n5<\/pre>\n<p>Here, the for loop helps us to print out the contents of the <strong>numbers<\/strong> list through each iteration.<\/p>\n<p>It is important to note that the for loop must be indented properly, otherwise, we will get an <strong>IndentationError<\/strong>.<\/p>\n<h2>Python For Loop using Python range()<\/h2>\n<p>One common use of <strong>for loops in Python<\/strong> is to iterate over a range of numbers using the <strong>range()<\/strong> function. The <strong>range()<\/strong> function generates a sequence of numbers within a specified range.<\/p>\n<p>The basic syntax for using the range() function is as follows:<\/p>\n<pre><code class=\"language-python\">range(start, stop, step)\r\n<\/code><\/pre>\n<p>Here, the <strong>start<\/strong> is the first number in the range (default is 0). The <strong>stop<\/strong> is the last number in the range (this number is not included in the range). The <strong>step<\/strong> is the difference between each number in the range (default is 1).<\/p>\n<p>Example of Python for and range function-<\/p>\n<pre><code class=\"language-python\">for i in range(2, 10, 2):\r\n    print(i)\r\n<\/code><\/pre>\n<p>The output for this code will be:<\/p>\n<pre>2\r\n4\r\n6\r\n8<\/pre>\n<p>Here, we see that using the <strong>range()<\/strong> function in a for loop in Python we are able to print out the numbers between 2 and 10(excluded) with a difference of 2 digits.<\/p>\n<p>It&#8217;s important to note that when using <strong>range()<\/strong> in a for loop, the loop variable (i.e., <strong>i<\/strong> in the above example) will take on the value of the next number in the range on each iteration, rather than the next item in a list or other iterable object.<\/p>\n<p>The <strong>range()<\/strong> function is very useful for performing a specific number of iterations or for generating a sequence of numbers for use in mathematical operations or other calculations. Moreover, the range() function can also be converted to a <a href=\"https:\/\/tutorpython.com\/tutorial\/list-in-python\" target=\"_blank\" rel=\"noopener\">list<\/a>, <a href=\"https:\/\/tutorpython.com\/tutorial\/tuples-in-python\" target=\"_blank\" rel=\"noopener\">tuple<\/a>, or <a href=\"https:\/\/tutorpython.com\/tutorial\/sets-in-python\" target=\"_blank\" rel=\"noopener\">set<\/a> with the use of <strong>list()<\/strong>, <strong>tuple(),<\/strong> or <strong>set()<\/strong>.<\/p>\n<h2>For loop in Python with index<\/h2>\n<p>Sometimes it is useful to know the index of the current item in a loop.<\/p>\n<p>Python provides the built-in function <code>enumerate()<\/code> which can be used in combination with the for loop to get the index of the current item.<\/p>\n<p>The syntax of For loop is as follows-<\/p>\n<pre><code class=\"language-python\">for index, variable in enumerate(sequence):\r\n    # code to execute for each iteration\r\n<\/code><\/pre>\n<p>Example of For loop in Python with index-<\/p>\n<pre><code class=\"language-python\">fruits = [\"apple\", \"banana\", \"cherry\"]\r\nfor index, fruit in enumerate(fruits):\r\n    print(index, fruit)\r\n<\/code><\/pre>\n<p>The output of this will be:<\/p>\n<pre><code class=\"language-python\">0 apple\r\n1 banana\r\n2 cherry\r\n<\/code><\/pre>\n<p>Here, it prints each element and its corresponding index in the list <strong>fruits<\/strong> on a new line.<\/p>\n<p>The <strong>enumerate()<\/strong> function returns a tuple, where the first element is the index and the second element is the value of the current item in the loop.<\/p>\n<p><strong>Note<\/strong>: When we are looping through a collection, it is a good practice to use the <strong>enumerate()<\/strong> function instead of using the <strong>range()<\/strong> function with the length of the collection and the index to access the elements directly. This is because it makes your code more readable.<\/p>\n<h2>For Loop with Else statement<\/h2>\n<p>In Python, the for loop can be used in conjunction with an<a href=\"https:\/\/tutorpython.com\/tutorial\/if-else-python\" target=\"_blank\" rel=\"noopener\"> <strong>else<\/strong> block<\/a>. The else block is executed after the loop completes, but only if the loop completes normally (i.e., without being interrupted by a <strong>break<\/strong> statement).<\/p>\n<p>The syntax for a for loop with an else block is as follows:<\/p>\n<pre><code class=\"language-python\">for variable in sequence:\r\n    # code to execute on each iteration\r\nelse:\r\n    # code to execute after the loop completes\r\n<\/code><\/pre>\n<p>Example using the above syntax:<\/p>\n<pre><code class=\"language-python\">numbers = [1, 2, 3, 4, 5]\r\nfor num in numbers:\r\n    print(num)\r\nelse:\r\n    print(\"Loop complete.\")\r\n<\/code><\/pre>\n<p>The output for this code will be:<br \/>\n<code>1<br \/>\n2<br \/>\n3<br \/>\n4<br \/>\n5<br \/>\nLoop complete.<\/code><\/p>\n<p>Here, we are using a <strong>for<\/strong> loop with an <strong>else<\/strong> block to iterate over a list of numbers and print each one. If the loop completes normally, the else block will print &#8220;<strong>Loop complete<\/strong>&#8220;.<\/p>\n<p>This is useful for situations where we want to perform certain actions after the loop completes, but only if the loop completes normally. For example, we might use an <strong>else<\/strong> block to check for errors or missing data after processing a large dataset, or to <a href=\"https:\/\/tutorpython.com\/tutorial\/basic-input-output-operations-in-python\" target=\"_blank\" rel=\"noopener\">display a message<\/a> to the user after a successful operation.<\/p>\n<p><strong>Note: <\/strong>If the loop is interrupted by a <strong>break<\/strong> statement, the <strong>else<\/strong> block will not be executed. So it&#8217;s important to keep that in mind when using <strong>else<\/strong> block with <strong>for<\/strong> loop.<\/p>\n<h4>Conclusion<\/h4>\n<p>For loops in Python is an essential tool for Python programmers. Whether you are a beginner or an experienced developer, understanding how to use for loops effectively is crucial for writing efficient and effective code.<\/p>\n<p>In this article, we&#8217;ve covered the basics of the <strong>standard for loop<\/strong>, including how to iterate over sequences and use the <strong>range()<\/strong> function. We&#8217;ve also learned about the <strong>&#8220;for-each&#8221; loop<\/strong> and how it differs from the standard for loop. Then we saw how to use <strong>else<\/strong> statements in for loops.<\/p>\n<p>There are other types of loops in Python as well<\/p>\n<ul>\n<li><a href=\"https:\/\/tutorpython.com\/tutorial\/while-loop-in-python\" target=\"_blank\" rel=\"noopener\">while loop in python<\/a><\/li>\n<li>do while loop in python<\/li>\n<\/ul>\n<p>Hope you like the tutorial, learn Python with the help of a <a href=\"https:\/\/tutorpython.com\/\" target=\"_blank\" rel=\"noopener\">Python tutor<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will learn about the different types of for&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[28],"tags":[],"class_list":["post-7216","post","type-post","status-publish","format-standard","hentry","category-tutorial"],"acf":[],"_links":{"self":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/7216","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/comments?post=7216"}],"version-history":[{"count":18,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/7216\/revisions"}],"predecessor-version":[{"id":8876,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/7216\/revisions\/8876"}],"wp:attachment":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/media?parent=7216"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/categories?post=7216"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/tags?post=7216"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}