With a list say {{x1, y1}, {x2, y2}, …} and a list {z1}, what is the best way to create a list {{x1, y1, z1}, {x2, y2, z1}, {x3, y3, z1}, …}?

  • $\begingroup$ Join[#, {z1}] & /@ {{x1, y1}, {x2, y2}} $\endgroup$
    – wuyudi
    Jan 23 at 8:20

You can use PadRight:

    {{x1, y1}, {x2, y2}},
    {Automatic, 3},

{{x1, y1, z1}, {x2, y2, z1}}

Or ArrayPad:

    {{x1, y1}, {x2, y2}, {x3, y3}},

{{x1, y1, z1}, {x2, y2, z1}, {x3, y3, z1}}

n = 1000000;
a = RandomReal[{-1, 1}, {n, 2}];
b = ConstantArray[0., 1];
c = Join[a, ConstantArray[b, Length[a]], 2]; // RepeatedTiming // First


xy = {{x1, y1}, {x2, y2}, ...}
z = {z1, z2, ...}
xyz = Partition[Flatten[Riffle[xy, z]], 3]

and you're done. Riffle also works with just one z-value: it'll do exactly what you asked, after re-reading your question more carefully.


First, Riffle[list1, list2 **or** element, so just z1 works, too] makes

{ {x1, y1}, z1, {x2, y2}, z2, ...}

then, Flatten[list] makes

{ x1, y1, z1, x2, y2, z2, ... }

finally, Partition[list, 3] turns it into

{ {x1, y1, z1}, {x2, y2, z2}, ...}
  • $\begingroup$ This is NOT what the question asked though. The question wanted to add a single constant z1 element to the right of each sublist. $\endgroup$
    – MarcoB
    Jan 22 at 23:03
  • 1
    $\begingroup$ @MarcoB I think the question is open to question. The OP uses the term "a list {z1}` rather than just z1 and the above answer works whether there's a single term in the list ({z1}) or multiple terms ({z1,z2,z3}) or just a single constant (z1). I also say that because of the odd use of compilation rather than concatenation. $\endgroup$
    – JimB
    Jan 22 at 23:57
  • $\begingroup$ @JimB I see. On the other hand, in their post OP included a "desired output" with a constant z1, and they accepted an answer using a constant z1... I ready the "list {z1}" to mean "a list containing a single element, z1". Plenty of functions in MMA return a list even when the output is a single element, for consistency, so I could see the requirement being described that way in a simplified MWE. Either way, I'll edit and retract the downvote, since it's clearly not as cut-and-dried to everybody as it was to me on first read. $\endgroup$
    – MarcoB
    Jan 23 at 2:22

If z1 is a list (as indicated in the question), then does the following do what you want:

z1 = {1, 2, 3};
xy = {{x1, y1}, {x2, y2}, {x3, y3}};
Flatten[{#, z1}] & /@ xy
(* {{x1, y1, 1, 2, 3}, {x2, y2, 1, 2, 3}, {x3, y3, 1, 2, 3}} *)

Or should the output be as follows:

z = {z1, z2, z3};
xy = {{x1, y1}, {x2, y2}, {x3, y3}};
Flatten[{#, zz}] & /@ xy /. zz -> z
(* {{x1, y1, {z1, z2, z3}}, {x2, y2, {z1, z2, z3}}, {x3, y3, {z1, z2, z3}}} *)

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.