Delete element in an array for julia Delete element in an array for julia arrays arrays

Delete element in an array for julia


You can also go with filter!:

a = Any["D", "A", "s", "t"]filter!(e->e≠"s",a)println(a)

gives:

Any["D","A","t"]

This allows to delete several values at once, as in:

filter!(e->e∉["s","A"],a)

Note 1: In Julia 0.5, anonymous functions are much faster and the little penalty felt in 0.4 is not an issue anymore :-) .

Note 2: Code above uses unicode operators. With normal operators: is != and e∉[a,b] is !(e in [a,b])


Several of the other answers have been deprecated by more recent releases of Julia. I'm currently (Julia 1.1.0) using something like

function remove!(a, item)    deleteat!(a, findall(x->x==item, a))end

You can also use findfirst if you'd prefer, but it doesn't work if a does not contain item.


Depending on the usage, it's also good to know setdiff and it's in-place version setdiff!:

julia> setdiff([1,2,3,4], [3])3-element Array{Int64,1}: 1 2 4

However, note that it also removes all repeated elements, as demonstrated in the example:

julia> setdiff!([1,2,3,4, 4], [3])3-element Array{Int64,1}: 1 2 4