Equivalent of “for X in [list]” or “foreach”

In Python, we can evaluate an expression over specific values of x in a list.

Example:

a = [4,5,6] # this is a list
x = range(len(a)) # this is pointer
for i in x:
print a[i] # should print a[] elements


Many other languages call this operation foreach instead of for.

Is there a way to accomplish the same in Mathematica?

• You've seen Map[] and Table[], no? Additionally, a lot of built-in functions are Listable, so that level of indirection isn't even needed. – J. M. is away Sep 12 '17 at 1:36
• The equivalent in Mathematica uses Do: a = {1, 2, 3}; Do[Print[i], {i, a}]. Python list comprehensions can be translated using Table. As @J.M. says, using Map and listability, this type of loop is often not necessary in Mathematica. – Simon Rochester Sep 12 '17 at 2:19
• In fact, even in @Simon's example, you don't need a loop variable if you use Scan[]: Scan[Print, a]. – J. M. is away Sep 12 '17 at 2:20
• @J.M. No I am familar with loop constructs like Do[] to achieve that. Not Map[] or Table[]. I am trying to retrieve array elements via mapping for example in Python: a = [4,5,6] x = range(len(a)) for i in x: print a[i] – Rene Duchamp Sep 12 '17 at 12:04
• Right, so that was actually a nudge for you to look them up in the documentation! – J. M. is away Sep 12 '17 at 12:05

There are several constructs you can use. The one that comes closest to the foreach of other languages is

a = {1, 2, 3};
Do[Print[i], {i, a}]


Note that unlike in Python, the iterator variable i is local to Do.

There's an analogous Table syntax. In Mathematica, we use Table much more frequently than Do.

Map and Scan are also useful alternatives to Table and Do, for example Scan[Print, a].

Further variants of these are discussed in Applying Functions to Lists.

Finally, many functions in Mathematica have the Listable attribute, which means that they automatically Map over lists:

SetAttributes[f, Listable]

f[{1, 2, 3}]
(* {f[1], f[2], f[3]} *)


To be more precise, they automatically MapThread over sets of lists:

f[{1, 2, 3}, {a, b, c}]
(* {f[1, a], f[2, b], f[3, c]} *)

• This should fit OP's description too: Function[i, Print[i]] /@ a – Kuba Sep 12 '17 at 8:25
• @Kuba I did not want to complicate it by introducing a pure function just for the sake of showing an extra i. I do think it is an important and common question though, for people coming from other languages. That's why I added the foreach keyword to the title. – Szabolcs Sep 12 '17 at 8:32
• Great answer. May want to mention the fact that Mathematica tends towards local scoping in functions. i.e. in your Do example the variable i is defined only within the loop. In the Python construct i is global and retains the last value of the list after the for loop completes. Something more akin to: Scan[(i=#;f[i])&,a]; – John Joseph M. Carrasco Sep 12 '17 at 8:50