# Map substitution of variable in expression

If I have an expression involving a variable x, like 2x+1, and I have a list of different possible x values, like {1,2,3}, is there a short way to "map" the expression over the list, returning a new list? This is one way I found:

(2x+1) /. x -> # & /@ {1,2,3}


But that has a lot of symbols in between the (2x+1) and the {1,2,3}. Is there a shorter way?

The expression might not necessarily be distributive over a list so (2x+1) /. x -> {1,2,3} won't work.

• Does Function[x, 2 x + 1] /@ {1, 2, 3} suit your needs? How about Table[2 x + 1, {x, {1, 2, 3}}]? Commented Jan 30, 2020 at 4:18
• If you do not like using those #,/@ symbols, you could always write ReplaceAll[(2 x + 1), x -> {1, 2, 3}] Commented Jan 30, 2020 at 4:33
• @J.M. That Table method seems much more readable. Thanks. Commented Jan 30, 2020 at 4:57
• Also this would work: (2 x + 1) /. x -> Range[3] Commented Jan 30, 2020 at 8:40

### Function shorthand

A short way is to use this Function notation:

(x \[Function] 2 x + 1) /@ {1, 2, 3}      (* output: {3, 5, 7} *)


In a Notebook this formats as:

The \[Function] operator can be entered with EscfnEsc.

### Cases

Nasser's suggestion does not meet your requirements because it relies on listability just as (2x+1) /. x -> {1,2,3} does. However you can invert the rule like this:

Cases[{1, 2, 3}, x_ :> 2 x + 1]           (* output: {3, 5, 7} *)


By using Rule rather than RuleDelayed you can also use an external definition:

foo = 2 x + 1;

Cases[{1, 2, 3}, x_ -> foo]               (* output: {3, 5, 7} *)


### Table

Since this answer has been Accepted (thank you) I shall include J. M.'s recommendation of Table for completeness.

Table[2 x + 1, {x, {1, 2, 3}}]            (* output: {3, 5, 7} *)


Like Cases this can use external definitions if needed:

foo = 2 x + 1;
v = {1, 2, 3};
Table[foo, {x, v}]                        (* output: {3, 5, 7} *)


To apply each rule separately, we wrap it with List

2 x + 1 /. {{x -> 1}, {x -> 2}, {x -> 3}}


{3, 5, 7}

This translates to

2 x + 1 /. List /@ Thread[x -> {1, 2, 3}]


{3, 5, 7}

Introducing the attribute Listable in your function:

Function[x, 2  x + 1, Listable]@{1, 2, 3}

(*{3, 5, 7}*)