When I meet the situation I can do it in javascript, I always think if there's an foreach function it would be convenience. By foreach I mean the function which is described below:
def foreach(fn,iterable): for x in iterable: fn(x) they just do it on every element and didn't yield or return something,i think it should be a built-in function and should be more faster than writing it with pure Python, but I didn't found it on the list,or it just called another name?or I just miss some points here?
Maybe I got wrong, cause calling an function in Python cost high, definitely not a good practice for the example. Rather than an out loop, the function should do the loop in side its body looks like this below which already mentioned in many python's code suggestions:
def fn(*args): for x in args: dosomething but I thought foreach is still welcome base on the two facts:
- In normal cases, people just don't care about the performance
- Sometime the API didn't accept iterable object and you can't rewrite its source.
13 Answers
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] 7Python 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 map can be used for the situation mentioned in the question.
E.g.
map(len, ['abcd','abc', 'a']) # 4 3 1 For functions that take multiple arguments, more arguments can be given to map:
map(pow, [2, 3], [4,2]) # 16 9 It returns a list in python 2.x and an iterator in python 3
In case your function takes multiple arguments and the arguments are already in the form of tuples (or any iterable since python 2.6) you can use itertools.starmap. (which has a very similar syntax to what you were looking for). It returns an iterator.
E.g.
for num in starmap(pow, [(2,3), (3,2)]): print(num) gives us 8 and 9
4The correct answer is "python collections do not have a foreach". In native python we need to resort to the external for _element_ in _collection_ syntax which is not what the OP is after.
Python is in general quite weak for functionals programming. There are a few libraries to mitigate a bit. I helped author one of these infixpy
from infixpy import Seq (Seq([1,2,3]).foreach(lambda x: print(x))) 1 2 3 Also see: Left to right application of operations on a list in Python 3
1Yes, although it uses the same syntax as a for loop.
for x in ['a', 'b']: print(x) 3Here is the example of the "foreach" construction with simultaneous access to the element indexes in Python:
for idx, val in enumerate([3, 4, 5]): print (idx, val) 1This does the foreach in python 3
test = [0,1,2,3,4,5,6,7,8,"test"] for fetch in test: print(fetch) 1Look at this article. The iterator object nditer from numpy package, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.
Example:
import random import numpy as np ptrs = np.int32([[0, 0], [400, 0], [0, 400], [400, 400]]) for ptr in np.nditer(ptrs, op_flags=['readwrite']): # apply random shift on 1 for each element of the matrix ptr += random.choice([-1, 1]) print(ptrs) d:\>python nditer.py [[ -1 1] [399 -1] [ 1 399] [399 401]] 1If I understood you right, you mean that if you have a function 'func', you want to check for each item in list if func(item) returns true; if you get true for all, then do something.
You can use 'all'.
For example: I want to get all prime numbers in range 0-10 in a list:
from math import sqrt primes = [x for x in range(10) if x > 2 and all(x % i !=0 for i in range(2, int(sqrt(x)) + 1))] I know this is an old thread but I had a similar question when trying to do a codewars exercise.
I came up with a solution which nests loops, I believe this solution applies to the question, it replicates a working "for each (x) doThing" statement in most scenarios:
for elements in array: while elements in array: array.func() If you're just looking for a more concise syntax you can put the for loop on one line:
array = ['a', 'b'] for value in array: print(value) Just separate additional statements with a semicolon.
array = ['a', 'b'] for value in array: print(value); print('hello') This may not conform to your local style guide, but it could make sense to do it like this when you're playing around in the console.
If you really want you can do this:
[fn(x) for x in iterable] But the point of the list comprehension is to create a list - using it for the side effect alone is poor style. The for loop is also less typing
for x in iterable: fn(x)