1
$\begingroup$

I have a nested list (ie., one list containing lists) and I want to replace parts of the nested lists.

list = {
  {"a", "b", "Take whatever is in here"}
}

I want to have the following result

{
  {"c", "d", "Take whatever is in here"}
}

My approach was using Replace[] and a placeholder. However, how do I get the content of the placeholder?

{{"a", "b", _} -> {"c", "d", **???**}}
$\endgroup$
  • 5
    $\begingroup$ Try list /. {"a", "b", x_} :> {"c", "d", x} . Note the use of :> instead of -> . $\endgroup$ – LouisB Sep 22 '17 at 7:08
  • $\begingroup$ Top! You can just copy it as answer :) $\endgroup$ – Dennis Sep 22 '17 at 7:17
  • $\begingroup$ @LouisB could you copy it as answer, so I can accept your solution? Thanks! $\endgroup$ – Dennis Sep 28 '17 at 16:17
1
$\begingroup$

I thought this was straightforward to find in the docs, but, apparently, this is an edge-case.

Assuming we know only, as the OP put it, the "placeholder" _, the documentation provides the following suggestive example:

In[1]:= f[x_] := (x + 1)^2
In[2]:= {f[1], f[a + b c]}
Out[2]= {4, (1 + a + b c)^2}

which might give a hint about the x_ construct.

It's very helpful to search for, e.g., "named patterns" in the documentation. Check this as a starting point, but do read through the many other linked pages as well. Patterns are probably the most important and fundamental part of Mathematica and are one of the first things to learn.

I'll leave it to @LouisB to post the actual answer from the comments if he so wishes.

| improve this answer | |
$\endgroup$
1
$\begingroup$

The way we get the contents of the placeholder is to give the blank pattern a name. Then we refer to the name, as follows

Clear[x]
list = {{"a", "b", "Take whatever is in here"}};
list /. {"a", "b", x_} -> {"c", "d", x}  (* do not use this *)

(*  {{"c", "d", "Take whatever is in here"}}  *)

The code above produces the right answer, this time, but it is not recommended. We notice that Mathematica uses different color coding for the x_ on the left and x on the right. Why aren't they the same?

What would happen if we forgot to Clear[x] and x already had a value?

x = "bug";
list /. {"a", "b", x_} -> {"c", "d", x}  (* do not use this *)

(*  {{"c", "d", "bug"}}  *)

In the above, if we Clear[x] we would lose its value. We could use a different name, like y, but the real solution is to use RuleDelayed (:>) instead of Rule (->), as

x = "bug";
list /. {"a", "b", x_} :> {"c", "d", x} 

(*   {{"c", "d", "Take whatever is in here"}}   *)

Now we notice the color coding for x_ and x is the same (in Mathematica). They are both local variables, instead of one local and one global.

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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