Is there a ‘foreach’ function in Python 3?

Every occurence of “foreach” I’ve seen (PHP, C#, …) does basically the same as pythons “for” statement.

These are more or less equivalent:

// PHP:
foreach ($array as $val) {
    print($val);
}

// C#
foreach (String val in array) {
    console.writeline(val);
}

// Python
for val in array:
    print(val)

So, yes, there is a “foreach” in python. It’s called “for”.

What you’re describing is an “array map” function. This could be done with list comprehensions in python:

names = ['tom', 'john', 'simon']

namesCapitalized = [capitalize(n) for n in names]

Leave a Comment