# Pattern matching in nested lists

I'm sure this has been asked before, but I can't find the right combination of search keywords to find it. Apologies.

I want to do a ReplaceAll on a list of lists, for example, I would like:

{{a, b}, {c, d}} /. {i_, j_} -> {i, j, 0}


What I want is to turn this list into {{a,b,0}, {c,d,0}}, but I can't figure out a way to tell Mathematica to only look at lists that are one level "below". Running the above returns {{a, b}, {c, d}, 0}, as i matched {a,b} and j matched {c,d}.

How do I pattern match lists that nested?

• Either use Replace with the correct level specification or narrow your pattern, perhaps by using the contents of the list: {i_Integer, j_Integer} or something like that if possible. I would post an answer, but I'm very positive this is a duplicate... Either way, hope that helped.
– rm -rf
Nov 11, 2013 at 0:39
• Replace is the way to go, but you could also map a ReplaceAll as in #/.{_,_}:>...&/@list. Use :> instead of -> so that it works even when i and j have a value
– Rojo
Nov 11, 2013 at 0:42
• You could also use VectorQ[]: list /. v_?VectorQ -> PadRight[v, 1]. May 27, 2015 at 23:48

One way to do this is to build a simple function and then map the function onto the list you want to change:

f[{a_, b_}] := {a, b, 0};
f /@ {{a, b}, {c, d}, {e, f}, {1, 2}}
{{a, b, 0}, {c, d, 0}, {e, f, 0}, {1, 2, 0}}


Or you could use ReplaceRepeated:

{{a, b}, {c, d}, {e, f}, {1, 2}} //. {i_, j_} :> {i, j, 0}
{{a, b, 0}, {c, d, 0}, {e, f, 0}, {1, 2, 0}}


Just for variety (more complex nesting may require modification):

{{a, b}, {c, d}} /. {i_?AtomQ, j_?AtomQ} -> {i, j, 0}


or

Insert[#, 0, -1] & /@ {{a, b}, {c, d}}


or

Append[#, 0] & /@ {{a, b}, {c, d}}


Without the use of rules i mention the following 2 solutions :

PadRight[{{a, b}, {c, d}}, {2, 3}]

Transpose[Append[Transpose[{{a, b}, {c, d}}], {0, 0}]]


I often use such solutions to be able to compile my scripts.

Cases works

lst = {{a, b}, {c, d}};
Cases[lst, {i_, j_} :> {i, j, 0}] Similarly,

lst = {{a, b}, {c, d}, {e, f}, {1, 2}}
Map[Append[#, 0] &, lst]

{{a, b, 0}, {c, d, 0}, {e, f, 0}, {1, 2, 0}}

• This is ubpdqn's third solution. For variety, consider PadRight[]. May 27, 2015 at 23:46