I would like to have an array of tuples. However it seems I cannot append a tuple to it. Here is a minimal code example that raises the error.
julia> a = [(1,1),(2,2)]
2-element Array{Tuple{Int64,Int64},1}:
(1, 1)
(2, 2)
julia> append!(a, (3,3) )
ERROR: MethodError: Cannot `convert` an object of type Int64 to an object of type Tuple{Int64,Int64}
This may have arisen from a call to the constructor Tuple{Int64,Int64}(...),
since type constructors fall back to convert methods.
Stacktrace:
[1] _append!(::Array{Tuple{Int64,Int64},1}, ::Base.HasLength, ::Tuple{Int64,Int64}) at ./array.jl:644
[2] append!(::Array{Tuple{Int64,Int64},1}, ::Tuple{Int64,Int64}) at ./array.jl:637
Is something wrong with my syntax? I don't get why it complains that it has to convert a number to a tuple. What gives?
append!
adds all of the individual elements of another collection to the existing object. Julia raises the error here because (3, 3)
is a collection of two integers and it cannot reconcile an individual integer of type Int64
with the array's Tuple{Int64,Int64}
type.
The method you need is push!
, which will add one or more individual items to an existing collection:
julia> push!(a, (3, 3))
3-element Array{Tuple{Int64,Int64},1}:
(1, 1)
(2, 2)
(3, 3)
The individual item, the tuple (3, 3)
, was successfully pushed onto the array a
.
To accomplish the same task with append!
, the tuple needs to be contained in a collection of some sort itself, such as an array:
julia> append!(a, [(4, 4)])
4-element Array{Tuple{Int64,Int64},1}:
(1, 1)
(2, 2)
(3, 3)
(4, 4)
This is documented on the collections page here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With