Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python foreach Loop
1
Python foreach Loop

5/5 – (1 vote)

[Image: 1f4a1.png] Question: Does Python have a
Code:
for each
or
Code:
foreach
loop? If so, how does it work? If not, what is the alternative?

This article will shed light on these questions. I’ll give you the summary first and dive into the details later:

[Image: python_foreach_loop-1024x576.jpg]

Python has three alternatives to the “for each” loop:

  1. A simple
    Code:
    for ... in ...
    loop


  2. A
    Code:
    map()
    function


  3. A list comprehension statement.

You’ll learn about those alternatives in the following paragraphs, so keep reading!

Let’s get started with the most important question:

What is a “Foreach Loop”?

Definition: A
Code:
foreach
or
Code:
for each
loop is a programming control flow statement for iterating over elements in a sequence or collection. Unlike other loop constructs, the
Code:
foreach
loop iterates over all elements rather than maintaining a counter, loop variable, or checking a condition after each loop iteration.

[Image: image-198-1024x576.png][i]Figure: Example of a for each loop (pseudocode) that iterates over elements 10, 20, and 30 and prints their value.[/i]

Here are three examples of a
Code:
foreach
loop in three different programming languages PHP, C#, and Perl:

Code:
// 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 $_; }
Does Python have a foreach Loop?

The Python language doesn’t support the keywords
Code:
foreach
or
Code:
for each
loops in a literal syntactical way. However, “for each” in Python is done using the “for … in …” expression.
For example, to iterate over each element in the list
Code:
[10, 20, 30]
in Python, you’d write
Code:
for x in [10, 20, 30]
.

Here’s a full Python code example with semantical equivalence to a “foreach” statement:

Code:
# 'foreach' or 'for each' in Python is done using 'for' for x in [10, 20, 30]: print(x)

Output:

Code:
10 20 30

[Image: 1f30d.png] Learn More: Feel free to check out our full article on Python loops on the Finxter blog.

“For Each” Meaning “Apply Function to Each Element”

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 map function functionality in Python.

Many programming languages with “for each” support provide a syntax that applies a function to each element of an iterable like so:

Code:
# Other programming languages: foreach(function, iterable)

This can be done in Python by means of the
Code:
map()
function:

Code:
# Python: map(function, iterable)

Here’s a simple example of how you’d use the
Code:
map()
function in Python that applies the function
Code:
f
to each element of the list
Code:
[1, 2, 3]
, incrementing each of its elements by 1 to obtain
Code:
[2, 3, 4]
:

Code:
lst = [1, 2, 3] def f(x): return x + 1 print(map(f, lst)) # [2, 3, 4]

You can watch my explainer video on
Code:
map()
in the following video:



[Image: 1f30d.png] Learn More: Feel free to check out our full article on
Code:
map()
on the Finxter blog.

“For Each” as Python List Comprehension

Python’s list comprehension feature is syntactical sugar to create a new iterable by applying a (possibly identity) function to each element of an existing iterable.

[Image: 1f4a1.png] Many coders would view the list comprehension 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.

List comprehension is a compact way of creating lists. The simple formula is
Code:
[expression + context]
.
  • Expression: What to do with each list element?

  • Context: What elements to select? The context consists of an arbitrary number of
    Code:
    for
    and
    Code:
    if
    statements.

The example
Code:
[x+10 for x in [1, 2, 3]]
creates the list
Code:
[11, 12, 13]
.

Code:
lst = [1, 2, 3] new_lst = [x+10 for x in lst] print(new_lst) # [11, 12, 13]

You can watch my explainer video on list comprehension in case you’re interested in how it works:



[Image: 1f30d.png] Learn More: Feel free to check out our full article on Python list comprehension on the Finxter blog.

Programmer Humor

[Image: image-163.png][i]It’s hard to train deep learning algorithms when most of the positive feedback they get is sarcastic. — from xkcd[/i]
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: