[Tut] Python foreach Loop - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] Python foreach Loop (/thread-99659.html) |
[Tut] Python foreach Loop - xSicKxBot - 07-03-2022 Python foreach Loop <div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{"align":"left","id":"446871","slug":"default","valign":"top","reference":"auto","count":"1","readonly":"","score":"5","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})"}"> <div class="kksr-stars"> <div class="kksr-stars-inactive"> <div class="kksr-star" data-star="1" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="2" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="3" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="4" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="5" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> <div class="kksr-stars-active" style="width: 142.5px;"> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> </div> <div class="kksr-legend"> 5/5 – (1 vote) </div> </div> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" 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> <p>This article will shed light on these questions. I’ll give you the summary first and dive into the details later:</p> <figure class="wp-block-image size-large"><img loading="lazy" 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="(max-width: 1024px) 100vw, 1024px" /></figure> <p><strong>Python has three alternatives to the “for each” loop:</strong></p> <ol> <li><strong>A simple <code>for ... in ...</code> loop</strong></li> <li><strong>A <code>map()</code> function</strong></li> <li><strong>A list comprehension statement.</strong></li> </ol> <p>You’ll learn about those alternatives in the following paragraphs, so keep reading! </p> <p>Let’s get started with the most important question:</p> <h2>What is a “Foreach Loop”?</h2> <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> <div class="wp-block-image"> <figure class="aligncenter size-large"><img 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="(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> </div> <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> <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 foreach ($set as $value) { // Do something to $value; } // C# foreach (String val in array) { console.writeline(val); } // Perl foreach (1, 2, 3, 4) { print $_; }</pre> <h2>Does Python have a foreach Loop?</h2> <p class="has-global-color-8-background-color has-background"><strong>The Python language doesn’t support the keywords <code>foreach</code> or <code>for each</code> loops in a literal syntactical way. However, “for each” in Python is done using the “for … in …” 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’d write <code>for x in [10, 20, 30]</code>. </p> <p>Here’s a full Python code example with semantical equivalence to a “foreach” statement:</p> <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' for x in [10, 20, 30]: print(x)</pre> <p>Output:</p> <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 20 30</pre> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f30d.png" alt="?" 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> <h2>“For Each” Meaning “Apply Function to Each Element”</h2> <p>If you’re reading this and you haven’t been satisfied with the answers provided so far, chances are that you’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> <p>Many programming languages with “for each” support provide a syntax that <strong>applies a function to each element of an iterable</strong> like so:</p> <pre class="wp-block-preformatted"><code># Other programming languages:</code> <code>foreach(function, iterable)</code></pre> <p>This can be done in Python by means of the <code>map()</code> function:</p> <pre class="wp-block-preformatted"><code># Python: map(function, iterable)</code></pre> <p>Here’s a simple example of how you’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> <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)) # [2, 3, 4]</pre> <p>You can watch my explainer video on <code>map()</code> in the following video:</p> <figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"> <div class="wp-block-embed__wrapper"> <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> </div> </figure> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f30d.png" alt="?" 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> <h2>“For Each” as Python List Comprehension</h2> <p>Python’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> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Many coders would view the <strong>list comprehension</strong> feature as Python’s way to provide a functional “foreach” statement because it enables you to perform a function “for each” element of an iterable such as a sequence.</p> <p>List comprehension is a compact way of creating lists. The simple formula is <code>[expression + context]</code>.</p> <ul> <li><strong>Expression:</strong> What to do with each list element?</li> <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> </ul> <p>The example <code>[x+10 for x in [1, 2, 3]]</code> creates the list <code>[11, 12, 13]</code>.</p> <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] new_lst = [x+10 for x in lst] print(new_lst) # [11, 12, 13]</pre> <p>You can watch my explainer video on list comprehension in case you’re interested in how it works:</p> <figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"> <div class="wp-block-embed__wrapper"> <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> </div> </figure> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f30d.png" alt="?" 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> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Programmer Humor</h2> <div class="wp-block-image"> <figure class="aligncenter size-full is-resized"><a href="https://imgs.xkcd.com/comics/computers_vs_humans.png" target="_blank" rel="noreferrer noopener"><img 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="(max-width: 578px) 100vw, 578px" /></a><figcaption><em>It’s hard to train deep learning algorithms when most of the positive feedback they get is sarcastic.</em> — 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> </div> </div> https://www.sickgaming.net/blog/2022/06/30/python-foreach-loop/ |