# 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. Aug 17, 2023 at 12:41
• Similar 263048 Aug 25, 2023 at 22:24

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

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

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

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

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


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 one

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


Another way using Cases:

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

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