What are common mistakes in julia that beginners should aware of?

I would like to point out that if your elements are not immutable and you change inside them (not this specific case) copy is not enough, you need to use deepcopy to make a copy of each element (recursively).

2 Likes

The reason is that in general we have:

to_index(i::Bool) = throw(ArgumentError("invalid index: $i of type Bool"))

so Bool indexing should be disallowed. However, in Julia Base some methods have custom implementations of getindex that does not fall back to to_index.

3 Likes

It would be good to clean it up for Julia 2.0 (probably not possible before because it is technically breaking).
Is there already an issue for it?

I think the reason Bool doesn’t count as an integer for indexing purposes is to avoid confusing with logical indexing:

julia> v = ["a", "b"];

julia> v[[1, 1]] # vector of indices, also v[[1,2,1,2,1]] or v[[CartesianIndex(2)]]
2-element Vector{String}:
 "a"
 "a"

julia> v[[true, true]] # logical indexing, also v[v .== "a"]
2-element Vector{String}:
 "a"
 "b"

I presume that Tuple(v)[true] working is an oversight, since logical indexing does still work there: Tuple(v)[[true, false]]. Maybe Tuple and NamedTuple indexing corner cases · Issue #29417 · JuliaLang/julia · GitHub is the issue.

4 Likes

Yes, see https://github.com/JuliaLang/julia/pull/31829 and https://github.com/JuliaLang/julia/issues/31726

4 Likes

I tried to sum up a lot of the discussion that took place here in a single post, feel free to check it out and let me know if there are other things that should be added in a subsequent post: Tricky concepts in Julia for beginners (and how to overcome them) | by Logan Kilpatrick | Sep, 2022 | Medium

4 Likes

Something on the lines of this would be useful as well: Common allocation mistakes

2 Likes