Josep Espasa
Josep Espasa

Reputation: 759

Convert a Set to an Array in Julia

How can I convert a Set to an Array in Julia?

E.g. I want to transform the following Set to an Array.

x = Set([1,2,3])

x
Set{Int64} with 3 elements:
  2
  3
  1

Upvotes: 10

Views: 4058

Answers (4)

Marco Meer
Marco Meer

Reputation: 81

You can use a comprehension:

x = Set(1:5)
@time y = [i for i in x]
> 0.000006 seconds (2 allocations: 112 bytes)
typeof(y)
> Vector{Int64} (alias for Array{Int64, 1})

Upvotes: 2

Francis King
Francis King

Reputation: 1732

You can use [ ] to create an array.

x = Set([1,2,3])
y = [a for a in x]

y

2
3
1

typeof(y)
Vector{Int64} (alias for Array{Int64, 1})

Upvotes: 1

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42244

You can also use the splat operator on sets:

julia> [x...]
3-element Vector{Int64}:
 2
 3
 1

However, this is slower than collect.

Upvotes: 1

Josep Espasa
Josep Espasa

Reputation: 759

The collect() function can be used for this. E.g.

collect(x)
3-element Vector{Int64}:
 2
 3
 1

Notice, however, that the order of the elements has changed. This is because sets are unordered.

Upvotes: 14

Related Questions