# How to get this list with a terse method [duplicate]

If I have like

{a,b}

and I want to get

 {{a+1,b},{a-1,b},{a,b+1},{a,b-1}}


We don't care about the ordering of the list.Such as the {{a-1,b},{a+1,b},{a,b+1},{a,b-1}} also is a valid list.

This is current method

MapAt[Reverse,
Transpose[{Distribute[Unevaluated@Plus[{1, -1}, {a, b}], List],
Riffle[{b, b}, {a, a}]}], {{2}, {4}}]


{{1+a,b},{a,1+b},{-1+a,b},{a,-1+b}}

Or this

Catenate@({Tuples[{Plus[#, {1, -1}], {#2}}],
Tuples[{{#}, Plus[#2, {1, -1}]}]} & @@ {a, b})


{{1+a,b},{-1+a,b},{a,1+b},{a,-1+b}}

Very ugly code.Are there more beautiful solution can do this?

• lis = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; {a, b} + # & /@ lis Commented Apr 3, 2016 at 10:38
• ...or {a, b} + # & /@ Join[#, -#] &[IdentityMatrix[2]]. Replace Join[] with Riffle[] if desired. Commented Apr 3, 2016 at 10:39
• @J.M. Yes, much nicer. Commented Apr 3, 2016 at 10:43
• Table[{a, b}, 4] + Join[#, -#] &[IdentityMatrix[2]] Commented Apr 3, 2016 at 10:48
• @RunnyKine Thanks a lots. :)
– yode
Commented Apr 3, 2016 at 10:50

The following approach will be very fast for large lists since it utilizes vectorization:

Table[{a, b}, 4] + Join[#, -#] &[IdentityMatrix[2]]


Just for fun:

Join @@ (# + {a, b} & /@ {#, -#} & /@ {{1, 0}, {0, 1}})

• Thanks.Catenate[# + {a, b} & /@ {#, -#} & /@ {{1, 0}, {0, 1}}]
– yode
Commented Apr 3, 2016 at 10:35

A double Transpose might be considered "beautiful", and it certainly can be very fast too.

Transpose[Transpose[{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}] + {a, b}]


Not as fast as some of the other methods, but a TranslationTransform approach is also possible:

TranslationTransform[{a,b}][{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}]


{{-1 + a, b}, {1 + a, b}, {a, -1 + b}, {a, 1 + b}}

  list = {a, b};
Partition[Flatten@Table[ReplacePart[
list, i -> list[[i]] + #] & /@ {1, -1}, {i, 1, 2}], 2]

(*{{1 + a, b}, {-1 + a, b}, {a, 1 + b}, {a, -1 + b}}*)