Reputation: 2005
I would like to convert an array to a python like list
in Julia.
To create an array of type
Any
one may initialize an empty array with this syntax array = []
. However if I want to perform conversion, i.e. lets take an array of type Array(Float64,1)
to type Any
, what would be the correct approach?
Or If there are any alternate approaches to create a list in Julia?
My approach to create a function which takes an array and convert it to type any:
function list(x)
x = convert(Any, x)
return x
end
x_test = [0.19, 0.03, 0.27]
t1 = typeof(x_test)
println("type of x_test is: $t1")
x_test = list(x_test)
t2 = typeof(x_test)
println("type of x_test is: $t2")
Output:
type of x_test is: Array{Float64,1}
type of x_test is: Array{Float64,1}
Please suggest a method or solution to achieve this conversion task.
Thanks.
Upvotes: 3
Views: 918
Reputation: 2995
You were not far, you just need to convert to an array of Any
:
julia> convert(Array{Any}, x_test)
3-element Vector{Any}:
0.19
0.03
0.27
But as others have said, it's not a good idea to hide type information in general because it will just slow things down.
Upvotes: 1
Reputation: 42214
The shortest form is Vector{Any}(a)
as in code here:
julia> a=[1,2,3]
3-element Vector{Int64}:
1
2
3
julia> Vector{Any}(a)
3-element Vector{Any}:
1
2
3
However, if you want to be able to hold in a copy of a
other elements such as String
s you will be much more efficient by strictly telling that:
julia> b = Vector{Union{eltype(a),String}}(a)
3-element Vector{Union{Int64, String}}:
1
2
3
julia> push!(b,"jan")
4-element Vector{Union{Int64, String}}:
1
2
3
"jan"
Upvotes: 5
Reputation: 13800
You can do:
julia> list(x) = Any[i for i ∈ x]
list (generic function with 1 method)
julia> list([0.19, 0.03, 0.25])
3-element Vector{Any}:
0.19
0.03
0.25
But as Oscar says in his comments, why would you ever want to do that? It's true that Python performance often suffers because of a lack of type information, that doesn't mean Julia becomes "like Python" if you deliberately prevent the compiler from optimizing (it will become a lot slower though in almost all cases!)
Upvotes: 6