How create constant list of integers

Suppose I have a given positive integer n. What are simple ways to create a list of length n consisting of all zeros exactly, that is, filled with the integer 0?

For example, if n has value 5, then I want to create [0, 0, 0, 0, 0] but without explicitly entering five zeros.

zeros(Int, n) or fill(0, n)

5 Likes

Does Julia have a replicate operator like the one in Python, where, for example, [0] * 5 produces the list [0, 0, 0, 0, 0]?

repeat([0], 5)
3 Likes

What about:
LinRange{Int}(0,0,n)

OK, repeat in Julia works as does python’s * replicate operator: it seems to apply generally, too – to strings, matrices, etc. Thank you.

I personally don’t think “* by a scaler → replication” is very intuitive mathematically

Where is * documented? I have not been able to find it in the docs at julialang.org or through online search elsewhere.

@murrayE, for strings, ^ is a replicator in Julia:

julia> "Julia"^5
"JuliaJuliaJuliaJuliaJulia"
1 Like

You also have Tuple or ntuple(x->1,6)

1 Like

hit ? in REPL and type * then hit Enter:

help?> *
search: *

...
.....

I think you should use zeros or fill rather than repeat. If you have a short list of constant length, known at compile time, you can consider a tuple or StaticArrays.jl.

2 Likes