6
$\begingroup$

If I start out with a list A with $n$ elements in it, how do I append elements to it until it has a length $N$?

For example if A={1,2,3,4}, and suppose I want to append the element 3.14 to A until the length of A is 10. I tried doing this with a While loop as follows:

While[Length[A]<10,Append[A,3.14]]

However Mathematica gets stuck computing it. How can one do this?

$\endgroup$

3 Answers 3

9
$\begingroup$

If you introduce a length bound already, there is absolutely no reason for Append/AppendTo. Such a loop with Append/AppendTo has runtime complexity $O(n^2)$ because Append/AppendTo has to perform a copy of the whole list (which grows longer and longer). So a better practice is to initialize A as a list with the maximal length, to introduce an iteration counter i that actually stores the current length of the list, and just to write into A[[i]]. This way, only one entry of A is updated and the loop has complexity $O(n)$.

n = 10;
A = ConstantArray[0., n];
A[[1;;4]] = Range[1.,4.];
i = 4;
While[i < n,
 ++i;
 A[[i]] = 3.14
 ]
$\endgroup$
0
7
$\begingroup$

Try

A={1,2,3,4};    
While[Length[A] < 10,
A = Append[A, 3.14]]

Which gives

{1, 2, 3, 4, 3.14, 3.14, 3.14, 3.14, 3.14, 3.14}

When you call Length[A] inside the loop using Append[] it only remembers the A that you originally defined, so you need to explicitly 'update' its value. As mentioned in the comment below, AppendTo[A, 3.14] should do the trick:

While[Length[A] < 10,
AppendTo[A, 3.14]]

Worth reading the documentation of AppendTo[].

$\endgroup$
1
  • 3
    $\begingroup$ it might be worth mentioning that AppendTo[A, 3.14] also works since AppendTo automatically updates A while Append does not. $\endgroup$
    – Nasser
    Apr 6, 2020 at 5:44
7
$\begingroup$

PadRight can be used.

In a general setting you will need to do PadRight[A, N, element].

As in this case, you can use PadRight[A, 10, 3.14] and assign that list to A itself for appending. This is much faster than While loop approach for larger sets.

A = PadRight[A,10,3.14]
(*{1, 2, 3, 4, 3.14, 3.14, 3.14, 3.14, 3.14, 3.14}*)

Another approach:

A = Join[A, ConstantArray[elem, N-n]]

Here, we can use

A = Join[A, ConstantArray[3.14, 6]]

Performance: (as on Intel i5, 8 GB RAM)

A = {1,2,3,4}
(A = PadRight[A, 3.14, 10^6])//RepeatedTiming

B = {1,2,3,4}
(B = Join[B, ConstantArray[3.14, 10^6-4]])//RepeatedTiming

A == B

{0.014, (a big list)}

{0.072, (a big list)}

True

$\endgroup$

Your Answer

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

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