Home > OS >  Julia equivalent to python list multiplication
Julia equivalent to python list multiplication

Time:03-15

In python I can quickly concatenate and create lists with repeated elements using the and * operators. For example:

my_list = [1] * 3   ['a'] * 4  # == [1, 1, 1, 'a', 'a', 'a', 'a']

Similarly in Julia, I can quickly concatenate and create strings with repeated elements using the * and ^ operators. For example:

my_string = "1"^3 * "a"^4  # == "111aaaa"

My question is whether or not there is a convenient equivalent for lists (arrays) in Julia. If not, then what is the simplest way to define arrays with repeated elements and concatenation?

CodePudding user response:

You can use repeat, e.g.

[repeat([1], 3); repeat(['a'],4)]

produces Any[1, 1, 1, 'a', 'a', 'a', 'a'].

CodePudding user response:

For the above scenario, a shorter form is fill:

[fill(1,3); fill('a', 4)]

You could also define a Python style operator if you like:

⊕(a::AbstractVector{T}, n::Integer) where T = repeat(a, n)
⊕(a::T, n::Integer) where T = fill(a, n)

The symbol can be entered in Julia by typing \oplus and pressing Tab.

Now you can do just as in Python:

julia> [1,2] ⊕ 2
4-element Vector{Int64}:
 1
 2
 1
 2

julia> 3 ⊕ 2
2-element Vector{Int64}:
 3
 3
  • Related