{"id":6762,"date":"2018-08-12T19:16:41","date_gmt":"2018-08-12T13:46:41","guid":{"rendered":"https:\/\/techbeamers.com\/?p=6762"},"modified":"2025-11-30T10:52:45","modified_gmt":"2025-11-30T15:52:45","slug":"python-for-loop","status":"publish","type":"post","link":"https:\/\/techbeamers.com\/python-for-loop\/","title":{"rendered":"Python For Loops (with Code Examples)"},"content":{"rendered":"\n<p>A for loop is a basic tool for performing iterative tasks. This tutorial covers the Python for loop syntax, flowchart, and multiple variations with examples. This makes it easy for you to learn loops and use them in your Python programs.<\/p>\n\n\n<figure class=\"wp-block-post-featured-image\"><img loading=\"lazy\" decoding=\"async\" width=\"700\" height=\"400\" src=\"https:\/\/techbeamers.com\/wp-content\/uploads\/2018\/08\/Python-for-loop-syntax-and-examples.png\" class=\"attachment-post-thumbnail size-post-thumbnail wp-post-image\" alt=\"Python for loop, syntax and examples\" style=\"object-fit:cover;\" srcset=\"https:\/\/techbeamers.com\/wp-content\/uploads\/2018\/08\/Python-for-loop-syntax-and-examples.png 700w, https:\/\/techbeamers.com\/wp-content\/uploads\/2018\/08\/Python-for-loop-syntax-and-examples-300x171.png 300w, https:\/\/techbeamers.com\/wp-content\/uploads\/2018\/08\/Python-for-loop-syntax-and-examples-150x86.png 150w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/><\/figure>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-python-for-loop-definition-syntax\">How to Use For Loops in Python<\/h2>\n\n\n\n<p>Python provides a simple syntax for using <em>for loops<\/em> in programs. They help iterate through different types of objects. Python supports seven sequence data types: standard\/Unicode strings, lists, tuples, byte arrays, and range objects. Sets and dictionaries also exist, but they are unordered collections rather than sequence types.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-how-to-use-for-loops-in-python\">Python For Loop Syntax<\/h3>\n\n\n\n<p>A for loop in Python requires at least two variables to work. The first is an iterable object, such as a list, tuple, or string. The second is a variable that stores successive values from the sequence. Check its syntax below:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted rb-list\"># Syntax: Python for loop<br>for iter in sequence:<br>    statements(iter)<\/pre>\n\n\n\n<ul class=\"wp-block-list rb-list\">\n<li>The <strong>&#8220;iter&#8221;<\/strong> represents the iterating variable. It gets assigned successive values from the input sequence.<\/li>\n\n\n\n<li>The <strong>&#8220;sequence&#8221;<\/strong>&nbsp;may refer to any of the following Python objects such as a list, a tuple, or a string.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-flowchart\">Python For Loop Flowchart<\/h3>\n\n\n\n<p>The for loop can include a single line or a block of code with multiple statements. Before executing the code inside the loop, the value from the sequence gets assigned to the iterating variable <strong>(&#8220;iter&#8221;)<\/strong>.<\/p>\n\n\n\n<p>Below is the <a href=\"https:\/\/techbeamers.com\/c-for-loop\/\" target=\"_blank\" rel=\"noreferrer noopener\">For loop flowchart<\/a> representation in Python:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><a href=\"https:\/\/techbeamers.com\/wp-content\/uploads\/2018\/08\/Regular-Python-for-loop-flowchart.png\"><img loading=\"lazy\" decoding=\"async\" width=\"293\" height=\"372\" src=\"https:\/\/techbeamers.com\/wp-content\/uploads\/2018\/08\/Regular-Python-for-loop-flowchart.png\" alt=\"Regular Python For Loop Flowchart\" class=\"wp-image-6940\"\/><\/a><figcaption class=\"wp-element-caption\">Regular Python For Loop Flowchart<\/figcaption><\/figure>\n<\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-python-for-loop-variations\">Python For Loop: Multiple Variations with Examples<\/h2>\n\n\n\n<p>You can use a for loop to iterate through various data types in Python. Let&#8217;s go through them one by one<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-python-for-loop-with-a-string\">Python For Loop with Strings, Lists, and Dictionaries<\/h3>\n\n\n\n<p>Let&#8217;s start with a simple example: printing all characters in a <a href=\"https:\/\/techbeamers.com\/python-strings-functions-and-examples\/\" data-type=\"post\" data-id=\"2119\" target=\"_blank\" rel=\"noreferrer noopener\">Python string<\/a> using a for loop.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Program to print the letters of a string<br>vowels = \"AEIOU\"<br>for iter in vowels:<br>    print(\"char:\", iter)<br><br>\"\"\" Output<br>char: A<br>char: E<br>char: I<br>char: O<br>char: U<br>\"\"\"<\/pre>\n\n\n\n<p>Now, we&#8217;ll see how to use the for loop with a <a href=\"https:\/\/techbeamers.com\/python-list\/\" data-type=\"post\" data-id=\"6703\" target=\"_blank\" rel=\"noreferrer noopener\">Python list<\/a>. To demonstrate, we&#8217;ll use a list of N numbers and compute their average.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Program to calculate the average of N integers\nint_list = [1, 2, 3, 4, 5, 6]\nsum = 0\nfor iter in int_list:\n    sum += iter\nprint(\"Sum =\", sum)\nprint(\"Avg =\", sum\/len(int_list))<\/pre>\n\n\n\n<p>Here is the output after executing the above code.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">\"\"\" Output\nSum = 21\nAvg = 3.5\n\"\"\"<\/pre>\n\n\n\n<p>Moving on, let&#8217;s see how a for loop works with nested lists. The code below demonstrates how to print each element of a <a href=\"https:\/\/techbeamers.com\/python-nested-lists\/\" data-type=\"post\" data-id=\"12148\" target=\"_blank\" rel=\"noreferrer noopener\">nested list in Python<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]<br><br>for row in matrix:<br>    for element in row:<br>        print(element, end=\" \")<br>    print()<\/pre>\n\n\n\n<p>Next, let&#8217;s see how to iterate over a <a href=\"https:\/\/techbeamers.com\/python-dictionary\/\" data-type=\"post\" data-id=\"6730\" target=\"_blank\" rel=\"noreferrer noopener\">dictionary in Python<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># A dictionary with mixed data types as keys<br>mix = {<br>    \"string\": 123,<br>    100: \"value\",<br>    (1, 2): [True, False],<br>    None: \"null\"<br>}<br><br># Iterate over the dictionary using enumerate()<br>for index, (key, value) in enumerate(mix.items()):<br>    print(f\"Item {index + 1}: Key = {key}, Value = {value}\")<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Python For Loop with range(), zip(), and enumerate()<\/h3>\n\n\n\n<p>The <a href=\"https:\/\/techbeamers.com\/python-range-function\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python range()<\/a> function generates a sequence of numbers at runtime.<\/p>\n\n\n\n<p>For example, a statement like <strong>range(0, 10)<\/strong> will generate a series of ten integers starting from 0 to 9. The snippet below shows how range() works and how you can access its elements by index.<\/p>\n\n\n\n<p><em>Note: In Python 3, range() returns a range object, not a list. You can convert it to a list if needed<\/em>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Check the type of list returned by range() function<br>print( type(range(0, 10)) )<br># &lt;class 'range'><br><br># Access the first element in the range sequence <br>print( range(0, 10)[0] )  # 0<br><br># Access the second element<br>print( range(0, 10)[1] )  # 1<br><br># Access the last element<br>print( range(0, 10)[9] )  # 9<br><br># Calculate the size of range list<br>print( len(range(0, 10)) )  # 10<\/pre>\n\n\n\n<p>Now, let&#8217;s see how range() works inside a for loop.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">for iter in range(0, 3):\n    print(\"iter: %d\" % (iter))<\/pre>\n\n\n\n<p>It will yield the following result.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">\"\"\" Output\niter: 0\niter: 1\niter: 2\n\"\"\"<\/pre>\n\n\n\n<p>By default, the for loop fetches elements from the sequence and assigns them to the iterating variable. But you can also make it return the index by <strong>replacing the sequence<\/strong> with a <strong>range(len(seq))<\/strong> expression.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">books = ['C', 'C++', 'Java', 'Python']\nfor index in range(len(books)):\n   print('Book (%d):' % index, books[index])<\/pre>\n\n\n\n<p>The following lines will get printed.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">\"\"\" Output\nBook (0): C\nBook (1): C++\nBook (2): Java\nBook (3): Python\n\"\"\"<\/pre>\n\n\n\n<p>The <a href=\"https:\/\/techbeamers.com\/python-zip\/\" data-type=\"post\" data-id=\"7523\" target=\"_blank\" rel=\"noreferrer noopener\">Python zip()<\/a> function lets you iterate over multiple lists simultaneously, pairing items based on their position.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">list1 = [1, 2, 3]<br>list2 = [\"a\", \"b\"]<br>for x, y in zip(list1, list2):<br>    print(x, y)  # Output: 1 a, 2 b<\/pre>\n\n\n\n<p>Next, let&#8217;s see how the <a href=\"https:\/\/techbeamers.com\/python-enumerate\/\" data-type=\"post\" data-id=\"11806\" target=\"_blank\" rel=\"noreferrer noopener\">Python enumerate()<\/a> helps when iterating with a for loop.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">mix = [\"hello\", 42, True, (1, 2), None]<br><br>for index, element in enumerate(mix):<br>    print(f\"Item {index + 1}: {element}\")<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-for-loop-with-else-clause\">More Python For Loop Examples<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">For loop with else clause<\/h4>\n\n\n\n<p>Interestingly, Python allows an optional <em>else statement<\/em> with the <em>for loop<\/em>. The code inside the <em>else clause<\/em> runs only if the loop completes without encountering a <em>break statement<\/em>.<\/p>\n\n\n\n<p>Check the below syntax to use the <em>else clause<\/em> with the loop.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">for item in seq:<br>    statement 1<br>    statement 2<br>    if &lt;condition>:  # If this condition is met, loop breaks<br>        break<br>else:<br>    statements  # Runs only if loop completes normally<\/pre>\n\n\n\n<p>Check out the flowchart below to understand how the <em>else clause<\/em> works with a <em>for loop<\/em>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><a href=\"https:\/\/techbeamers.com\/wp-content\/uploads\/2018\/08\/Python-for-loop-with-else-clause-flowchart.png\"><img loading=\"lazy\" decoding=\"async\" width=\"535\" height=\"423\" src=\"https:\/\/techbeamers.com\/wp-content\/uploads\/2018\/08\/Python-for-loop-with-else-clause-flowchart.png\" alt=\"Python for loop with else clause flowchart\" class=\"wp-image-6941\"\/><\/a><\/figure>\n<\/div>\n\n\n<p><a id=\"for-else-example\"><\/a>Below is the sample code that uses a for loop and an else statement.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Demonstrating else with for loop<br>birds = ['Belle', 'Coco', 'Juniper', 'Lilly', 'Snow']<br>ignore_else = False  # Improved variable name for clarity<br><br>for bird in birds:<br>    print(bird)<br>    if ignore_else and bird == 'Snow':<br>        break<br>else:<br>    print(\"No birds left.\")<\/pre>\n\n\n\n<p>The code prints all bird names and, if the loop runs fully, it executes the <em>else<\/em> block.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-nested-for-loops\">Nested for loops<\/h4>\n\n\n\n<p>A nested for loop is a loop inside another loop. It&#8217;s useful for iterating over multi-dimensional data, like lists of lists.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">for i in range(5):<br>    for j in range(3):<br>        if i == 2 and j == 1:<br>            break<br>        print(i, j)<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-for-loop-with-pass\">For loop with pass<\/h4>\n\n\n\n<p>A <em>pass<\/em> statement inside a for loop does nothing &#8211; it acts as a placeholder when you need a loop structure but don&#8217;t want to execute any code.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">for num in range(10):<br>    if num % 2 == 0:<br>        continue  # Skip even numbers<br>    pass  # Placeholder statement<br>    print(num)<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-for-loop-with-break\">For loop with break<\/h4>\n\n\n\n<p>A <em>break<\/em> statement stops a for loop before it completes all iterations. It is useful when you want to exit the loop based on a condition.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">numbers = [1, 2, 3, 4, 5]<br>for num in numbers:<br>    if num > 3:<br>        break  # Exit loop when num > 3<br>    print(num)<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-for-loop-in-one-line\">For loop in one line<\/h4>\n\n\n\n<p>A Python for loop can be written in a single line for conciseness. This is useful for simple operations on each element in a sequence.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">for num in range(10): print(f\"Number {num}: {num ** 2}\")<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-before-you-leave\">Summary: Python For Loop with Examples<\/h2>\n\n\n\n<p>In this tutorial, we explained the concept of Python for Loop&nbsp;with several examples so that you can easily use it in real-time Python programs. However, if you have any questions about this topic, please do write to us.<\/p>\n\n\n\n<p>Enjoyed this tutorial? Support us by subscribing to our <a href=\"https:\/\/youtube.com\/@techbeamers\" target=\"_blank\" rel=\"noreferrer noopener\">YouTube channel<\/a> and sharing this post on LinkedIn or Twitter! Your support helps us keep creating free, high-quality content.<\/p>\n\n\n\n<p><strong>Happy Coding,<br>TechBeamers.<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>A for loop is a basic tool for performing iterative tasks. This tutorial covers the Python for loop syntax, flowchart, and multiple variations with examples. This makes it easy for you to learn loops and use them in your Python programs. How to Use For Loops in Python Python provides a simple syntax for using [&hellip;]<\/p>\n","protected":false},"author":321,"featured_media":6764,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","jetpack_post_was_ever_published":false},"categories":[92],"tags":[7143],"class_list":{"0":"post-6762","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-python-programming-tutorials","8":"tag-programming"},"jetpack_featured_media_url":"https:\/\/techbeamers.com\/wp-content\/uploads\/2018\/08\/Python-for-loop-syntax-and-examples.png","_links":{"self":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/6762","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/users\/321"}],"replies":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/comments?post=6762"}],"version-history":[{"count":1,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/6762\/revisions"}],"predecessor-version":[{"id":23568,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/6762\/revisions\/23568"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/media\/6764"}],"wp:attachment":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/media?parent=6762"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/categories?post=6762"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/tags?post=6762"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}