4
$\begingroup$

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.

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

3 Answers 3

9
$\begingroup$

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:

enter image description here

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} *)

Recommended reading:


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} *)
$\endgroup$
1
$\begingroup$

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}

$\endgroup$
1
$\begingroup$

Introducing the attribute Listable in your function:

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

(*{3, 5, 7}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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