3
$\begingroup$

If I have a list such as list={1,2,3,4,5}, how can a prepend multiple values to the list?. For example what I want is to prepend 6 zeros prior to {1,2,3,4,5} to get {0,0,0,0,0,0,1,2,3,4,5}. I tried using Prepend[list, Table[0, 6]] but this give me {{0,0,0,0,0,0},1,2,3,4,5} which would be all the six zeros as the first element rather than each zero being an element.

Thank you.

$\endgroup$

3 Answers 3

5
$\begingroup$

You have lots of options, such as:

list = {1, 2, 3, 4, 5};
zeros = ConstantArray[0, 3];

Catenate[{zeros, list}]

(* or *)

Join[zeros, list]

(* or *)

Flatten[{zeros, list}, 1]

{0, 0, 0, 1, 2, 3, 4, 5}

As of Mathematica 12.1, you also have this option:

{Splice[zeros], Splice[list]}

{0, 0, 0, 1, 2, 3, 4, 5}

Which I guess is equivalent to doing this, which also works in earlier versions:

{Sequence @@ zeros, Sequence @@ list}

{0, 0, 0, 1, 2, 3, 4, 5}

But Splice has the additional advantage that it is not evaluated before it occurs in the context of a list, which means that we can use it with Prepend, and salvage your initial attempt:

Prepend[list, Splice[zeros]]

{0, 0, 0, 1, 2, 3, 4, 5}

(Prepend[list, Sequence @@ zeros] would not have have worked since Sequence would have been applied immediately, which nicely highlights the utility of the Splice.)

$\endgroup$
3
  • $\begingroup$ Thank you very much ! $\endgroup$
    – John
    Commented Apr 30, 2020 at 22:51
  • $\begingroup$ You can of course do Prepend[{1, 2, 3, 4, 5}, Unevaluated[Sequence @@ {0, 0, 0}]], but Splice[] is surely easier to handle. $\endgroup$ Commented May 2, 2020 at 14:22
  • $\begingroup$ @J.M. good point, thanks. $\endgroup$
    – C. E.
    Commented May 2, 2020 at 16:34
4
$\begingroup$

It sounds like you want to Join two lists.

$\endgroup$
1
  • $\begingroup$ Thank you @Szabolcs! That's exactly what I was looking for. $\endgroup$
    – John
    Commented Apr 30, 2020 at 22:32
4
$\begingroup$

You can also use ArrayPad and PadLeft:

ArrayPad[list, {6, 0}]
{0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5}
PadLeft[list, 6 + Length@list]
 {0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5}
$\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.