Is there a 'foreach' function in Python 3? Is there a 'foreach' function in Python 3? python python

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);}// Pythonfor 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]


Python doesn't have a foreach statement per se. It has for loops built into the language.

for element in iterable:    operate(element)

If you really wanted to, you could define your own foreach function:

def foreach(function, iterable):    for element in iterable:        function(element)

As a side note the for element in iterable syntax comes from the ABC programming language, one of Python's influences.


Other examples:

Python Foreach Loop:

array = ['a', 'b']for value in array:    print(value)    # a    # b

Python For Loop:

array = ['a', 'b']for index in range(len(array)):    print("index: %s | value: %s" % (index, array[index]))    # index: 0 | value: a    # index: 1 | value: b