241

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:

  1. In normal cases, people just don't care about the performance
  2. Sometime the API didn't accept iterable object and you can't rewrite its source.
8
  • 4
    What's wrong with just using a for loop?
    – user395760
    Commented Aug 18, 2013 at 0:30
  • 1
    This is exactly what for is for. Commented Aug 18, 2013 at 1:02
  • 3
    nothing wrong with for loop ,just for convenience Commented Aug 18, 2013 at 1:12
  • 15
    @user2357112, it's desirable to have a shorthand for calling a function once per item of a list. list.each(func) is cleaner than for item in list: func(item), IMO. The problem is that Python's done a good job of replacing functional favorites like map() and filter() with list comprehensions which simply extend its built-in for and if (which are homogeneous and readable) and a specific .each() might go against that.
    – sevko
    Commented Dec 9, 2014 at 16:15
  • sum(0 for _ in map(f, seq)) is a readable workaround. Commented Jun 11, 2018 at 18:44

15 Answers 15

274

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]
7
  • 8
    It's not map(), because map() accumulates and returns a list, while foreach() doesn't. The difference could be quite expensive if you're iterating over a long list of items. Agreed that for() does the trick.
    – Canuck
    Commented Apr 8, 2015 at 17:10
  • 5
    I've seen this referred to as a for-in loop.
    – Vox
    Commented Jul 9, 2015 at 21:23
  • 11
    They asked about for function, but you answered with for statement. Commented Jun 12, 2018 at 7:08
  • 1
    @JohannesSchaub-litb thing is that he is right... 'for' in python is literally 'foreach' known in other languages...in tcl for eg a 'for' loop would be something like for {stuff ran on beginning of loop} {condition here} {stuff that runs on each iteration} {commands here...} eg: for {set x 1} {$x <= 10} {incr x} {puts $x} you can also add extra checks inside the iteration braces using ';'. To me would make more sense if he came here asking if python had a true 'for' loop
    – Francisco
    Commented Jan 18, 2019 at 7:40
  • 3
    @Francisco I'm also right in saying that earth isn't flat. But I won't add it as an answer. Commented Jan 18, 2019 at 17:44
77

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.

7
  • 16
    If you're doing this for side-effects, rather than for the result of the mapping, then using map in this way isn't really going to work in Python 3 where map is lazy. That is, it now returns an iterator, not an already computed list. The side-effects won't take place until you iterate through the resulting list. Commented Aug 18, 2013 at 0:38
  • That's true and certainly a valid point, but the question suggests the OP is probably not concerned with such subtleties. Commented Aug 18, 2013 at 0:41
  • @LaurenceGonsalves Thanks. I've edited to make the first example correct in Python 3. Commented Aug 18, 2013 at 0:48
  • This is ugly, it's almost as long as the for loop, and if the iterable is long (perhaps infinite) or the function return values are large, it breaks with a MemoryError. Commented Aug 18, 2013 at 1:05
  • 1
    Edited to remove the map discussion. Commented Jun 11, 2016 at 17:18
37

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
2
  • This is not a foreach construct instead it's a loop to emulate it. Commented Jul 8, 2022 at 5:53
  • yes it to emulate.
    – uingtea
    Commented Jul 8, 2022 at 12:26
16

The 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

pip install infixpy https://pypi.org/project/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

2
  • 3
    This is the answer I was looking for. Most of the other answers aren't clear about python lacking a built in for each in loop, and just provide work-arounds. Cheers! Commented Feb 3, 2022 at 19:07
  • 2
    This answer is good. most other answers are in defensive mode.
    – Jake
    Commented Nov 15, 2023 at 9:40
15

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

4
  • 3
    map and foreach have different meaning. map returns a list of result (which implies creating a list, or an enumerable structure, or a structure that will be consumed, and therefore not called right away), foreach calls the function on each item, ignoring the result.
    – njzk2
    Commented Jun 28, 2016 at 20:46
  • 1
    Foreach must return the result imediately. Saying that creating iterator instead of foreach is preferred is total crap. Commented Jul 12, 2016 at 18:35
  • 2
    Using map() when the result is ignored is an anti-pattern. You should use a for loop instead.
    – odie5533
    Commented Jul 23, 2019 at 14:22
  • 3
    Using map and ignoring the results will produce undesired results in Python 3 since map is now lazily evaluated only when the resulting list is consumed. If the result of the map is never consumed, the calls are never applied.
    – Dmitry B.
    Commented Dec 14, 2019 at 6:31
8

Yes, although it uses the same syntax as a for loop.

for x in ['a', 'b']: print(x)
3
  • 1
    Unfortunately this is not forEach
    – nehem
    Commented Feb 28, 2020 at 0:24
  • @nehem Wrap it in a function if you wish.
    – Caveman
    Commented May 4, 2020 at 13:07
  • @nehem See question
    – Caveman
    Commented May 8, 2020 at 16:16
8

Here 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)
1
  • 1
    This is brilliant! Much cleaner than for idx in range(len(myList)):\print(idx,myList[idx]) where myList=[3, 4, 5].
    – Armfoot
    Commented Dec 7, 2020 at 21:07
5

This does the foreach in python 3

test = [0,1,2,3,4,5,6,7,8,"test"]

for fetch in test:
    print(fetch)
1
  • 11
    This does not answer the question.
    – Boiethios
    Commented Apr 16, 2018 at 12:21
3

Look 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]]
1
  • Interesting but still not a foreach Commented Dec 19, 2020 at 10:02
3

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)
1
  • 1
    I scrolled past this answer, caught a glimpse of the list comprehension being used for side effects, and screeched to a halt, all ready to do the "don't use a list comprehension for side effects" spiel. Then scrolled back to the answer, read it, and realized you'd done it already :)
    – pho
    Commented Jan 27, 2023 at 4:39
2

If 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))]
2

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()
1

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.

1

In short, the functional programming way to do this is:

def do_and_return_fn(og_fn: Callable[[T], None]):
    def do_and_return(item: T) -> T:
        og_fn(item)
        return item
    return do_and_return

# where og_fn is the fn referred to by the question. 
# i.e. a function that does something on each element, but returns nothing.
iterable = map(do_and_return_fn(og_fn), iterable)

All of the answers that say "for" loops are the same as "foreach" functions are neglecting the point that other similar functions that operate on iters in python such as map, filter, and others in itertools are lazily evaluated.

Suppose, I have an iterable of dictionaries coming from my database and I want to pop an item off of each dictionary element when the iterator is iterated over. I can't use map because pop returns the item popped, not the original dictionary.

The approach I gave above would allow me to achieve this if I pass lambda x: x.pop() as my og_fn,

What would be nice is if python had a built-in lazy function with an interface like I constructed:

foreach(do_fn: Callable[[T], None], iterable: Iterable)

Implemented with the function given before, it would look like:

def foreach(do_fn: Callable[[T], None], iterable: Iterable[T]) -> Iterable[T]:
    return map(do_and_return_fn(do_fn), iterable)

# being called with my db code. 
# Lazily removes the INSERTED_ON_SEC_FIELD on every element:
doc_iter = foreach(lambda x: x.pop(INSERTED_ON_SEC_FIELD, None), doc_iter)
0

No there is no from functools import foreach support in python. However, you can just implement in the same number of lines as the import takes, anyway:

foreach = lambda f, iterable: (*map(f, iterable),)

Bonus: variadic support: foreach = lambda f, iterable, *args: (*map(f, iterable, *args),) and you can be more efficient by avoiding constructing the tuple of Nones

4
  • Assigning a lambda to a variable is a code-smell. If a foreach function is deemed a must-have (IMO it is not, since for loops exist), you might as well define a function and while you're at it, make it a regular for loop -- code isn't written on paper so lines of code don't cost more. See a similar answer here: stackoverflow.com/a/2682075/843953, where the comment echoes this sentiment. I must admit though, the use of deque is a cool trick.
    – pho
    Commented Jan 27, 2023 at 4:36
  • @PranavHosangadi Op wanted a from functools import foreach. My answer does it in the same number of lines, which I believe is more readable than doing it in multiple lines with def and for. Lines of code cost the reader. I'm a big believer in aggressive inlining and named lambdas. Does having a more readable, implementation really outweigh the cost of the clutter of multiple lines? Commented Jan 27, 2023 at 6:30
  • 2
    A reader is going to spend more time deciphering that lambda than a simple function that uses a for loop. People (especially once you've had some programming experience) read blocks of code, not lines. As for the separate "named lambda" issue: stackoverflow.com/questions/38381556/…
    – pho
    Commented Jan 27, 2023 at 6:36
  • @PranavHosangadi the reader should be able to tell from the spelling exactly what the function does, they don't need to understand the implementation to work on the code. I think named lambdas will become more and more popular. Python's completely wrong on lambdas imo. My proposed style is: More aggressively extracting functions (making the code more readable from good spellings) + More aggressively inlining the function implementations (trading off readability in the current scope for that outside) Commented Jan 27, 2023 at 7:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.