3
$\begingroup$

I have a list $\{x,y,z,w,p\}$ and I want to replace $x,y,w$ by $q$. This works

{x,y,z,w,p}/.{x->q, y->q, p->q} 

But is there a way to do this concisely? I tried the following, but doesn't work

{x,y,z,w,p}/.{(x || y || p) ->q} 

Thanks in advance for any help.

$\endgroup$
2
  • 1
    $\begingroup$ closely related: 88301, 84757 $\endgroup$ Commented Nov 25, 2016 at 7:50
  • $\begingroup$ @Kuba Thank you. $\endgroup$ Commented Nov 25, 2016 at 7:52

2 Answers 2

5
$\begingroup$
{x, y, z, w, p} /. Alternatives[x, y, p] -> q (* or *) {x, y, z, w, p} /. Thread[{x, y, p} -> q] 

{q, q, z, w, q}

$\endgroup$
0
1
$\begingroup$
list = {x, y, z, w, p}; rep = {x, y, p}; pos = Position[list, Alternatives @@ rep] 

{{1}, {2}, {5}}

Using MapAt to to replace with single symbol

MapAt[q &, pos] @ list 

{q, q, z, w, q}

Using SubsetMap to replace with different symbols (thanks, E. Chan-López)

SubsetMap[{q, r, s} &, list, pos] 

{q, r, z, w, s}

With ReplaceAt (new in 13.1) we can easily impose additional conditions

list = {x, 1, z, w, p}; ReplaceAt[_Symbol :> q, pos] @ list 

{q, 1, z, w, q}

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.