{"id":126133,"date":"2022-06-30T16:22:09","date_gmt":"2022-06-30T16:22:09","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=446871"},"modified":"2022-06-30T16:22:09","modified_gmt":"2022-06-30T16:22:09","slug":"python-foreach-loop","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/06\/30\/python-foreach-loop\/","title":{"rendered":"Python foreach Loop"},"content":{"rendered":"<div class=\"kk-star-ratings kksr-valign-top kksr-align-left \" data-payload=\"{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;446871&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\\\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;}\">\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\"> 5\/5 &#8211; (1 vote) <\/div>\n<\/div>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Question<\/strong>: Does Python have a <code>for each<\/code> or <code>foreach<\/code> loop? If so, how does it work? If not, what is the alternative?<\/p>\n<p>This article will shed light on these questions. I&#8217;ll give you the summary first and dive into the details later:<\/p>\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"576\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/python_foreach_loop-1024x576.jpg\" alt=\"Python For Each Loop\" class=\"wp-image-446922\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/python_foreach_loop-1024x576.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/python_foreach_loop-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/python_foreach_loop-768x432.jpg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/python_foreach_loop.jpg 1280w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<p><strong>Python has three alternatives to the &#8220;for each&#8221; loop:<\/strong><\/p>\n<ol>\n<li><strong>A simple <code>for ... in ...<\/code> loop<\/strong><\/li>\n<li><strong>A <code>map()<\/code> function<\/strong><\/li>\n<li><strong>A list comprehension statement.<\/strong><\/li>\n<\/ol>\n<p>You&#8217;ll learn about those alternatives in the following paragraphs, so keep reading! <\/p>\n<p>Let&#8217;s get started with the most important question:<\/p>\n<h2>What is a &#8220;Foreach Loop&#8221;?<\/h2>\n<p class=\"has-global-color-8-background-color has-background\"><strong>Definition<\/strong>: A <code>foreach<\/code> or <code>for each<\/code> loop is a programming control flow statement for iterating over elements in a sequence or collection. Unlike other loop constructs, the <code>foreach<\/code> loop iterates over all elements rather than maintaining a counter, loop variable, or checking a condition after each loop iteration.<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" loading=\"lazy\" width=\"1024\" height=\"576\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/image-198-1024x576.png\" alt=\"\" class=\"wp-image-446879\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/image-198-1024x576.png 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/image-198-300x169.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/image-198-768x432.png 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/image-198.png 1228w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption><em><strong>Figure<\/strong>: Example of a for each loop (pseudocode) that iterates over elements 10, 20, and 30 and prints their value.<\/em><\/figcaption><\/figure>\n<\/div>\n<p>Here are three examples of a <code>foreach<\/code> loop in three different programming languages <a href=\"https:\/\/blog.finxter.com\/php-developer-income-and-opportunity\/\" data-type=\"post\" data-id=\"202161\" target=\"_blank\" rel=\"noreferrer noopener\">PHP<\/a>, <a href=\"https:\/\/blog.finxter.com\/c-developer-income-and-opportunity\/\" data-type=\"post\" data-id=\"189360\" target=\"_blank\" rel=\"noreferrer noopener\">C#<\/a>, and <a href=\"https:\/\/blog.finxter.com\/perl-developer-income-and-opportunity\/\" data-type=\"post\" data-id=\"206108\" target=\"_blank\" rel=\"noreferrer noopener\">Perl<\/a>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ PHP\nforeach ($set as $value) { \/\/ Do something to $value;\n} \/\/ C#\nforeach (String val in array) { console.writeline(val);\n} \/\/ Perl\nforeach (1, 2, 3, 4) { print $_;\n}<\/pre>\n<h2>Does Python have a foreach Loop?<\/h2>\n<p class=\"has-global-color-8-background-color has-background\"><strong>The Python language doesn&#8217;t support the keywords <code>foreach<\/code> or <code>for each<\/code> loops in a literal syntactical way. However, &#8220;for each&#8221; in Python is done using the &#8220;for &#8230; in &#8230;&#8221; expression. <\/strong>For example, to iterate over each element in the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-lists\/\" data-type=\"post\" data-id=\"7332\" target=\"_blank\">list<\/a> <code>[10, 20, 30]<\/code> in Python, you&#8217;d write <code>for x in [10, 20, 30]<\/code>. <\/p>\n<p>Here&#8217;s a full Python code example with semantical equivalence to a &#8220;foreach&#8221; statement:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"2\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># 'foreach' or 'for each' in Python is done using 'for'\nfor x in [10, 20, 30]: print(x)<\/pre>\n<p>Output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">10\n20\n30<\/pre>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Learn More<\/strong>: Feel free to check out our <a href=\"https:\/\/blog.finxter.com\/python-loops\/\" data-type=\"post\" data-id=\"4596\" target=\"_blank\" rel=\"noreferrer noopener\">full article on Python loops<\/a> on the Finxter blog. <\/p>\n<h2>&#8220;For Each&#8221; Meaning &#8220;Apply Function to Each Element&#8221;<\/h2>\n<p>If you&#8217;re reading this and you haven&#8217;t been satisfied with the answers provided so far, chances are that you&#8217;re really searching for the <a href=\"https:\/\/blog.finxter.com\/python-map\/\" data-type=\"post\" data-id=\"242\" target=\"_blank\" rel=\"noreferrer noopener\">map function<\/a> functionality in Python. <\/p>\n<p>Many programming languages with &#8220;for each&#8221; support provide a syntax that <strong>applies a function to each element of an iterable<\/strong> like so:<\/p>\n<pre class=\"wp-block-preformatted\"><code># Other programming languages:<\/code>\n<code>foreach(function, iterable)<\/code><\/pre>\n<p>This can be done in Python by means of the <code>map()<\/code> function:<\/p>\n<pre class=\"wp-block-preformatted\"><code># Python:\nmap(function, iterable)<\/code><\/pre>\n<p>Here&#8217;s a simple example of how you&#8217;d use the <code>map()<\/code> function in Python that applies the function <code>f<\/code> to each element of the list <code>[1, 2, 3]<\/code>, incrementing each of its elements by 1 to obtain <code>[2, 3, 4]<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"6\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">lst = [1, 2, 3] def f(x): return x + 1 print(map(f, lst))\n# [2, 3, 4]<\/pre>\n<p>You can watch my explainer video on <code>map()<\/code> in the following video:<\/p>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"Mastering the Python Map Function [+Video]\" width=\"780\" height=\"439\" src=\"https:\/\/www.youtube.com\/embed\/tqph6mWC3m8?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe>\n<\/div>\n<\/figure>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Learn More<\/strong>: Feel free to check out our <a href=\"https:\/\/blog.finxter.com\/python-map\/\" data-type=\"post\" data-id=\"242\" target=\"_blank\" rel=\"noreferrer noopener\">full article on <code>map()<\/code><\/a> on the Finxter blog. <\/p>\n<h2>&#8220;For Each&#8221; as Python List Comprehension<\/h2>\n<p>Python&#8217;s <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" data-type=\"post\" data-id=\"1171\" target=\"_blank\" rel=\"noreferrer noopener\">list comprehension<\/a> feature is syntactical sugar to create a new iterable by applying a (possibly identity) function to each element of an existing iterable.<\/p>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> Many coders would view the <strong>list comprehension<\/strong> feature as Python&#8217;s way to provide a functional &#8220;foreach&#8221; statement because it enables you to perform a function &#8220;for each&#8221; element of an iterable such as a sequence.<\/p>\n<p>List comprehension is a compact way of creating lists. The simple formula is <code>[expression + context]<\/code>.<\/p>\n<ul>\n<li><strong>Expression:<\/strong> What to do with each list element?<\/li>\n<li><strong>Context:<\/strong> What elements to select? The context consists of an arbitrary number of <code>for<\/code> and <code>if<\/code> statements.<\/li>\n<\/ul>\n<p>The example <code>[x+10 for x in [1, 2, 3]]<\/code> creates the list <code>[11, 12, 13]<\/code>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"2\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">lst = [1, 2, 3]\nnew_lst = [x+10 for x in lst]\nprint(new_lst)\n# [11, 12, 13]<\/pre>\n<p>You can watch my explainer video on list comprehension in case you&#8217;re interested in how it works:<\/p>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"A Simple Introduction to List Comprehension in Python\" width=\"780\" height=\"439\" src=\"https:\/\/www.youtube.com\/embed\/9qsq2Vf48W8?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe>\n<\/div>\n<\/figure>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Learn More<\/strong>: Feel free to check out our <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" data-type=\"post\" data-id=\"1171\" target=\"_blank\" rel=\"noreferrer noopener\">full article on Python list comprehension<\/a> on the Finxter blog. <\/p>\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n<h2>Programmer Humor<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full is-resized\"><a href=\"https:\/\/imgs.xkcd.com\/comics\/computers_vs_humans.png\" target=\"_blank\" rel=\"noreferrer noopener\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/image-163.png\" alt=\"\" class=\"wp-image-435467\" width=\"578\" height=\"282\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/image-163.png 578w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/image-163-300x146.png 300w\" sizes=\"auto, (max-width: 578px) 100vw, 578px\" \/><\/a><figcaption><em>It&#8217;s hard to train deep learning algorithms when most of the positive feedback they get is sarcastic.<\/em> &#8212; from <a href=\"https:\/\/imgs.xkcd.com\/comics\/computers_vs_humans.png\" data-type=\"URL\" data-id=\"https:\/\/imgs.xkcd.com\/comics\/computers_vs_humans.png\" target=\"_blank\" rel=\"noreferrer noopener\">xkcd<\/a><\/figcaption><\/figure>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (1 vote) Question: Does Python have a for each or foreach loop? If so, how does it work? If not, what is the alternative? This article will shed light on these questions. I&#8217;ll give you the summary first and dive into the details later: Python has three alternatives to the &#8220;for each&#8221; loop: [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-126133","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/126133","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=126133"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/126133\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=126133"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=126133"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=126133"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}