Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

append! cuts strings into characters, push! doesn't [Julia]

Objective:
I need a tuple like (Float, string, int, string, int, string, int, ...).
Since I calculate the entries over the course of my program, I first add them to an array/vector.

Attempt:

my_array = []
append!(my_array, 0.1) 
append!(my_array, "ab") 
append!(my_array, 2) 

println(tuple(my_array...))

# Bad output
(0.1, 'a', 'b', 2)

Question:
How can I get

# Good output
(0.1, "ab", 2)

instead?

like image 997
Andreas Burger Avatar asked Dec 29 '25 19:12

Andreas Burger


1 Answers

The problem is not with the tuple construction, but an appearent misunderstanding of append!:

julia> append!(my_array, 0.1)

1-element Vector{Any}:
 0.1

julia> append!(my_array, "ab")
3-element Vector{Any}:
 0.1
  'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
  'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)

append! appends the elements of any iterable (under which scalar numbers are subsumed) individually to an array. Strings are iterables of characters.

Instead, use push!:

julia> my_array2 = []
Any[]

julia> push!(my_array2, 0.1)
1-element Vector{Any}:
 0.1

julia> push!(my_array2, "ab")
2-element Vector{Any}:
 0.1
  "ab"

julia> push!(my_array2, 2)
3-element Vector{Any}:
 0.1
  "ab"
 2

julia> Tuple(my_array2)
(0.1, "ab", 2)

(Unfortunately, this is inconsistent with append and extend from Python... but you get used to it.)

like image 197
phipsgabler Avatar answered Jan 01 '26 10:01

phipsgabler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!