Delete element in an array for julia

41,504

Solution 1

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])

Solution 2

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.

Solution 3

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

Solution 4

You can use deleteat! and findall(compatible with Julia>1.0) for this.

a=Any["D","A","s","t","s"]
deleteat!(a, findall(x->x=="s",a))

Output:

3-element Array{Any,1}:
"D"
"A"
"t"
Share:
41,504
user2820579
Author by

user2820579

Updated on July 09, 2022

Comments

  • user2820579
    user2820579 over 1 year

    I've been wandering for a while in the docs and in forums and I haven't found a built in method/function to do the simple task of deleting an element in an array. Is there such built-in function?

    I am asking for the equivalent of python's list.remove(x).

    Here's an example of naively picking a function from the box:

    julia> a=Any["D","A","s","t"]
    julia> pop!(a, "s")
    ERROR: MethodError: `pop!` has no method matching       
    pop!(::Array{Any,1},     ::ASCIIString)
    Closest candidates are:
      pop!(::Array{T,1})
      pop!(::ObjectIdDict, ::ANY, ::ANY)
      pop!(::ObjectIdDict, ::ANY)
      ...
    

    Here mentions to use deleteat!, but also doesn't work:

    julia> deleteat!(a, "s")
    ERROR: MethodError: `-` has no method matching -(::Int64, ::Char)
    Closest candidates are:
      -(::Int64)
      -(::Int64, ::Int64)
      -(::Real, ::Complex{T<:Real})
      ...
    
     in deleteat! at array.jl:621