7
$\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
    Commented Aug 17, 2023 at 12:41
  • $\begingroup$ Similar 263048 $\endgroup$
    – Rabbit
    Commented Aug 25, 2023 at 22:24

8 Answers 8

10
$\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$
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$
10
$\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$
8
$\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$
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$
5
$\begingroup$

Another way using Cases:

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

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

Some more possibilities

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

Using the operator form of Insert

Insert[a0, 1] /@ list

Using Thread

Flatten /@ Thread[{a0, list}]

Using Outer

First @ Outer[Join, {{a0}}, list, 1]

Using SequenceReplace (new in 11.3)

SequenceReplace[list, {{a_, b_} ..} :> {a0, a, b}]

All produce

{{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.