How do I access the elements of a set?

Hello,
I defined a set as below:

S = Set([11, 13, 17, 19])

How can I access the set element:

julia> S[1]
ERROR: MethodError: no method matching getindex(::Set{Int64}, ::Int64)
Stacktrace:
 [1] top-level scope
   @ REPL[4]:1

julia> S(1)
ERROR: MethodError: objects of type Set{Int64} are not callable
Stacktrace:
 [1] top-level scope
   @ REPL[5]:1

Thank you.

Sets aren’t ordered, so there isn’t a well-defined meaning of S[n].

You can still iterate over a Set, in which Julia picks some arbitrary order, e.g.

julia> for x in S
           @show x
       end
x = 13
x = 11
x = 17
x = 19

and you can convert it into an indexable array in this order with collect:

julia> a = collect(S)
4-element Vector{Int64}:
 13
 11
 17
 19

julia> a[1]
13

However, the fact that you want S[1] strongly suggests that you may be using the wrong data structure for your problem.

The key thing that a Set is good at is testing inclusion:

julia> 11 in S
true

julia> 12 in S
false

Why are you using a Set? What operations do you want to perform on your data?

6 Likes

Hello,
Thank you so much for your reply.
I am a beginner and learning Julia.

1 Like

If you just want to draw a (representative) element, you can use first(S) though (but no last).

1 Like