# How to terminate a loop when the length of a list reaches a certain length?

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?

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
]


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[].

• it might be worth mentioning that AppendTo[A, 3.14] also works since AppendTo automatically updates A while Append does not. Apr 6, 2020 at 5:44

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}