4

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.

Adrian
  • 165
  • 3

3 Answers3

9

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} *)
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
1

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}

eldo
  • 67,911
  • 5
  • 60
  • 168
1

Introducing the attribute Listable in your function:

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

({3, 5, 7})

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44