ConstantArray
ConstantArray
ConstantArray[ expr, n ] creates a list containing n copies of a given value.
Usages
ConstantArray[ expr, n ]
ConstantArray[ expr, n ] returns a list of length n in which every element is expr. expr can be any expression, including a list. n must be a non-negative integer.
| Example | in | out |
|---|---|---|
A list with 5 copies of the number 2. |
ConstantArray[ 2, 5 ] |
{2, 2, 2, 2, 2} |
A list with 3 copies of Sqrt[2]. |
ConstantArray[ Sqrt[2], 3 ] |
{Sqrt[2], Sqrt[2], Sqrt[2]} |
A list with n copies of x, where n is a script variable and x is not defined. |
n := 5 |
r = {x, x, x, x, x} |
A list with 2 copies of a list. |
ConstantArray[ {1,2}, 2 ] |
{ {1,2}, {1,2} } |
Details
- Zero copies:
ConstantArray[ 1, 0 ]returns{}.
| Invalid input | Result |
|---|---|
ConstantArray[ 1, -1 ] |
Error: the 2nd argument should be of non-negative integer |
ConstantArray[ 1, 2.5 ] |
Error: the 2nd argument should be of non-negative integer |
ConstantArray[ 1, 6/2 ] |
Error: the 2nd argument should be of non-negative integer. A fraction is not accepted, even if its value is an integer. |
ConstantArray[ 1, k ] (k not defined) |
Error: the 2nd argument should be of non-negative integer |
ConstantArray[ 1, 2, 3 ] |
Error: the number of arguments should be two |