6
$\begingroup$

Suppose I have some array

 A1 = {{a1, b1}, {a2, b2}, {a3, b3}};

For each list, I want to add element a0 at the beginning so that my output is

 {{a0, a1, b1}, {a0, a2, b2}, {a0, a3, b3}}

Without explicitly typing the first entries, how one can implement this? Further, what if I want to instead add some element at the end?

$\endgroup$
2
  • $\begingroup$ The available solutions for arbitrary lists of lists are more restricted than solutions for rectangular/tensor arrays. $\endgroup$
    – Michael E2
    Aug 17, 2023 at 12:41
  • $\begingroup$ Similar 263048 $\endgroup$
    – Rabbit
    Aug 25, 2023 at 22:24

7 Answers 7

10
$\begingroup$
Prepend[a0] /@ A1

{{a0, a1, b1}, {a0, a2, b2}, {a0, a3, b3}}

Also:

PadLeft[A1, {Automatic, 3}, a0]

Or:

A1 /. {a_, b_} :> {a0, a, b}

And the new ReplaceAt:

ReplaceAt[A1, x_ :> Sequence[a0, x], {All, 1}]
$\endgroup$
9
$\begingroup$
A1 = {{a1, b1}, {a2, b2}, {a3, b3}};

Join[{a0}, #] & /@ A1
Catenate[{{a0}, #}] & /@ A1
Replace[A1, {x__} :> {a0, x}, 1]
Transpose@Join[{ConstantArray[a0, Length@A1]}, Transpose@A1]
SequenceCases[A1, {{a_, b__} ..} :> {a0, a, b}]

{{a0, a1, b1}, {a0, a2, b2}, {a0, a3, b3}}

$\endgroup$
8
$\begingroup$

Join has also a (rarely used) last integer argument:

A1 = {{a1, b1}, {a2, b2}, {a3, b3}};

Join[ConstantArray[a0, {3, 1}], A1, 2]
$\endgroup$
7
$\begingroup$

Here are some ways:

{a0, ##} & @@@ A1
Prepend[#, a0] & /@ A1
Insert[#, a0, 1] & /@ A1
ArrayPad[A1, {{0}, {1, 0}}, a0]

All yield: {{a0, a1, b1}, {a0, a2, b2}, {a0, a3, b3}}

$\endgroup$
7
$\begingroup$
 ArrayFlatten[{{a0,A1}}]

(* {{a0, a1, b1}, {a0, a2, b2}, {a0, a3, b3}} *)
$\endgroup$
7
$\begingroup$

Another one

A1 = {{a1, b1}, {a2, b2}, {a3, b3}};
lista0 = Table[a0, {i, 1, Length@A1}];
ArrayReshape[Flatten[Transpose[{lista0, A1}]], {Length@A1, Length@A1}]
$\endgroup$
4
$\begingroup$

Another way using Cases:

Cases[A1, x_List :> Join[{a0}, x]]

(*{{a0, a1, b1}, {a0, a2, b2}, {a0, a3, b3}}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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