3

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?

1
  • check out fill() Commented Mar 14, 2022 at 19:39

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

3

You can use repeat, e.g.

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

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.