# How can I prepend an element to every list in a list of lists?

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?

• The available solutions for arbitrary lists of lists are more restricted than solutions for rectangular/tensor arrays. Commented Aug 17, 2023 at 12:41
• Similar 263048 Commented Aug 25, 2023 at 22:24

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}}

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}]


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

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

Join[ConstantArray[a0, {3, 1}], A1, 2]


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}]


Here are some ways:

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


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

 ArrayFlatten[{{a0,A1}}]

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


Another way using Cases:

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

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


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}}