{"id":1452,"date":"2023-08-24T22:35:38","date_gmt":"2023-08-24T17:05:38","guid":{"rendered":"https:\/\/geekpython.in\/?p=1452"},"modified":"2024-03-01T17:08:01","modified_gmt":"2024-03-01T11:38:01","slug":"nested-for-loops-in-python","status":"publish","type":"post","link":"https:\/\/geekpython.in\/nested-for-loops-in-python","title":{"rendered":"Understanding Nested for Loops in Python &#8211; How Does it Work"},"content":{"rendered":"\n<p>You may have used Python <code>for<\/code> loops to iterate through iterable objects in order to access them independently and perform various operations. You&#8217;re probably familiar with the concept of nested <code>for<\/code> loops as well.<\/p>\n\n\n\n<p>In Python, nested <code>for<\/code> loops are loops that have one or more <code>for<\/code> loops within them.<\/p>\n\n\n\n<p>Nested <code>for<\/code> loops have a structure that is similar to the following code:<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >for x in my_iterable:\n    for item in x:\n        print(item.upper())<\/pre><\/div>\n\n\n\n<p>You may have seen the use of nested <code>for<\/code> loops in the creation of various patterns of asterisk or hyphen symbols.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Working of Nested for Loops<\/h1>\n\n\n\n<p>A nested <code>for<\/code> loop is made up of both an outer loop and an inner loop. When observing the structure of the nested <code>for<\/code> loop mentioned earlier, you&#8217;ll observe that the initial part of the code represents an outer <code>for<\/code> loop, and within this outer <code>for<\/code> loop, there exists an inner <code>for<\/code> loop.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >for anything in article: # Outer for-loop\n    # Some code here\n    for everything in anything: # Inner for-loop\n        # Some code here<\/pre><\/div>\n\n\n\n<p>But how they go hand in hand and iterate through data. Let&#8217;s uncover the iteration process of nested <code>for<\/code> loops.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >my_iterable = [\"Sachin\", \"Rishu\", \"Yashwant\"]\n\nfor item in my_iterable:\n    for each_elem in item:\n        print(each_elem, end=\" \")<\/pre><\/div>\n\n\n\n<p>The outer loop accesses each item in <code>my_iterable<\/code>.<\/p>\n\n\n\n<p>For each item in the outer loop (e.g., <code>\"Sachin\"<\/code>), the inner loop iterates through each individual element in the item (e.g., <code>\"S\"<\/code>, <code>\"a\"<\/code>, <code>\"c\"<\/code>, <code>\"h\"<\/code>, <code>\"i\"<\/code>, <code>\"n\"<\/code>).<\/p>\n\n\n\n<p>The print statement prints each character with a space, producing output like <code>\"S a c h i n \"<\/code>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >S a c h i n R i s h u Y a s h w a n t<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Example of Nested for Loops<\/h3>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >names = [\"Sachin\", \"Rishu\", \"Yashwant\"]\ngames = [\"Cricket\", \"Snooker\"]\n\n\nfor item in names: # Outer loop\n    for game in games: # Inner loop\n        print(item, \"plays\", game)<\/pre><\/div>\n\n\n\n<p>The outer loop iterates through the <code>names<\/code> list (Sachin, Rishu, Yashwant).<\/p>\n\n\n\n<p>For each name in the outer loop, the inner loop iterates through the <code>games<\/code> list (Cricket, Snooker).<\/p>\n\n\n\n<p>The <code>print<\/code> statement combines the current name with each game to output sentences like &#8220;<code>Sachin plays Cricket<\/code>&#8221; and &#8220;<code>Sachin plays Snooker<\/code>&#8220;.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >Sachin plays Cricket\nSachin plays Snooker\nRishu plays Cricket\nRishu plays Snooker\nYashwant plays Cricket\nYashwant plays Snooker<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Nested for Loops with range() Function<\/h3>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >for i in range(1, 2):\n    for x in range(3):\n        for num in range(x):\n            print(num)<\/pre><\/div>\n\n\n\n<p>The above code might be a bit confusing, let&#8217;s break it down into pieces:<\/p>\n\n\n\n<p>The outer <code>for<\/code> loop (<code>for i in range(1, 2)<\/code>) executes once because the range is from <strong>1<\/strong> to <strong>2<\/strong> (not inclusive), resulting in a single iteration. This loop governs the number of times the inner loops are executed.<\/p>\n\n\n\n<p>The middle or inner <code>for<\/code> loop runs three times because of the range from <strong>0<\/strong> to <strong>2<\/strong>. The iterations produce the values <strong>0<\/strong>, <strong>1<\/strong>, and <strong>2<\/strong>.<\/p>\n\n\n\n<p>The innermost <code>for<\/code> loop&#8217;s behavior depends on the middle <code>for<\/code> loop because its range relies on the current value of the <code>x<\/code> variable.<\/p>\n\n\n\n<p>When the value of <code>x<\/code> is <strong>0<\/strong> (first iteration), the innermost loop won&#8217;t execute because the range is empty. When the value of <code>x<\/code> is <strong>1<\/strong> (second iteration), it runs for one time returning the value 0 due to the <code>range(1)<\/code>, and then finally when <code>x<\/code> is <strong>2<\/strong> (third iteration), it runs two times returning the values <strong>0<\/strong> and <strong>1<\/strong> due to the <code>range(2)<\/code>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >0\n0\n1<\/pre><\/div>\n\n\n\n<h1 class=\"wp-block-heading\">Application of Nested for Loops in Real World<\/h1>\n\n\n\n<p>There are various ways to use nested <code>for<\/code> loops. They come in handy when you need to perform multiple rounds of iterations, deal with layered data structures like lists inside dictionaries or lists within other lists for navigating through data, or when you want to process and analyze text by breaking it down into smaller parts.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example &#8211; Tokenizing Sentence into Words and Characters<\/h3>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >text = \"Hey, there! Welcome to GeekPython.\"\nsentences = text.split(\". \")   # Splitting the text into sentences\n\nprint(\"Tokenized Sentences into Words and Characters:\")\nfor sentence in sentences:\n    print(\"- Sentence:\", sentence)\n    words = sentence.split(\" \")  # Splitting sentence into words\n    for word in words:\n        print(\"  - Word:\", word)\n        for character in word:\n            print(\"    - Character:\", character)<\/pre><\/div>\n\n\n\n<p>The above code tokenizes (breaking sentences into small units) the text data into words and characters using the nested <code>for<\/code> loops. The code goes as follows:<\/p>\n\n\n\n<p>The text data is initially split into sentences using <code>text.split(\". \")<\/code>, where the period followed by a space is used as the delimiter.<\/p>\n\n\n\n<p>The outer <code>for<\/code> loop iterates through sentences and prints them. The current sentence is then split into words using <code>sentence.split(\" \")<\/code>.<\/p>\n\n\n\n<p>Then subsequent <code>for<\/code> loop iterates through the words of the current sentence and prints them.<\/p>\n\n\n\n<p>Additionally, a further nested <code>for<\/code> loop is nested within the word loop, which processes the characters within each word, one at a time.<\/p>\n\n\n\n<p>The inner <code>for<\/code> loops are executed for every cycle of the outer <code>for<\/code> loop. This signifies that the code&#8217;s process is repeated for each sentence. However, since the provided code only deals with one sentence, it executes just once.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >Tokenized Sentences into Words and Characters:\n- Sentence: Hey, there! Welcome to GeekPython.\n  - Word: Hey,\n    - Character: H\n    - Character: e\n    - Character: y\n    - Character: ,\n  - Word: there!\n    - Character: t\n    - Character: h\n    - Character: e\n    - Character: r\n    - Character: e\n    - Character: !\n  - Word: Welcome\n    - Character: W\n    - Character: e\n    - Character: l\n    - Character: c\n    - Character: o\n    - Character: m\n    - Character: e\n  - Word: to\n    - Character: t\n    - Character: o\n  - Word: GeekPython.\n    - Character: G\n    - Character: e\n    - Character: e\n    - Character: k\n    - Character: P\n    - Character: y\n    - Character: t\n    - Character: h\n    - Character: o\n    - Character: n\n    - Character: .<\/pre><\/div>\n\n\n\n<p>You could have also performed the tokenization of textual data by reading the data from the file and to do so, you just need to adjust your code as shown below:<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >with open(\"test.txt\") as file:\n    content = file.read()\n\n    sentences = content.split(\". \")\n\n    print(\"Tokenized sentences into words and characters:\")\n    for sentence in sentences:\n        print(\"- Sentence:\", sentence)\n        words = sentence.split(\" \")\n        for word in words:\n            print(\"  - Word:\", word)\n            for char in word:\n                print(\"    - Character:\", char)<\/pre><\/div>\n\n\n\n<h1 class=\"wp-block-heading\">Conclusion<\/h1>\n\n\n\n<p>Python&#8217;s <code>for<\/code> loops are employed to sequentially go through a series of data elements, allowing access to each of them individually. Furthermore, a single <code>for<\/code> loop can contain one or more additional <code>for<\/code> loops within it, a concept commonly known as nested <code>for<\/code> loops.<\/p>\n\n\n\n<p>In the context of nested <code>for<\/code> loops, during every iteration of the outer <code>for<\/code> loop, the inner <code>for<\/code> loop iterates through each item present in the respective iterable. To illustrate, consider the scenario of shopping: envision visiting various shops and inspecting the items they offer. You start by exploring the first shop, examining all its items, and then proceed to the next shop, repeating this process until you have surveyed all available shops.<\/p>\n\n\n\n<p>Let&#8217;s recall what you&#8217;ve learned:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>What are nested <code>for<\/code> loops in Python<\/li>\n\n\n\n<li>How nested <code>for <\/code>loops work<\/li>\n\n\n\n<li>Code examples of nested <code>for<\/code> loops<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\ud83c\udfc6<strong>Other articles you might be interested in if you liked this one<\/strong><\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/flash-messages-on-frontend-using-flask\">How to display messages using flash() in Flask app<\/a>?<\/p>\n\n\n\n<p>\u2705<a href=\"https:\/\/geekpython.in\/structure-flask-app-with-blueprint\" target=\"_blank\" rel=\"noreferrer noopener\">How to structure a Flask app using Blueprint<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/render-images-from-flask\">Upload and display images on the frontend using Flask in Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/str-and-repr-in-python\">Change string representation of the objects using __str__ and __repr__<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/connect-sqlite-database-with-flask-app\">How to connect the SQLite database with the Flask app using Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/implement-getitem-setitem-and-delitem-in-python\">How to implement __getitem__, __setitem__ and __delitem__ in Python<\/a>?<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That&#8217;s all for now<\/strong><\/p>\n\n\n\n<p><strong>Keep Coding\u270c\u270c<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>You may have used Python for loops to iterate through iterable objects in order to access them independently and perform various operations. You&#8217;re probably familiar with the concept of nested for loops as well. In Python, nested for loops are loops that have one or more for loops within them. Nested for loops have a [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1454,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"0","ocean_second_sidebar":"0","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"0","ocean_custom_header_template":"0","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"0","ocean_menu_typo_font_family":"0","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"0","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"off","ocean_gallery_id":[],"footnotes":""},"categories":[2],"tags":[12,31],"class_list":["post-1452","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python","tag-python3","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1452","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/comments?post=1452"}],"version-history":[{"count":1,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1452\/revisions"}],"predecessor-version":[{"id":1453,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1452\/revisions\/1453"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/1454"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=1452"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=1452"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=1452"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}