How to delete a selected element in a range construct in Julia?

Viewed 127

From here I found that in a range construct one cannot find and replace its elements via array functions... How can be do it anyway?

Suppose I want to delete the elements 2,6,7,8,13,19 in range(1, step=1, stop=21). Or more generally, suppose a is a random array that contains numbers in the range [1,21] and one wants to delete these elementes in the given range.

2 Answers

You cannot delete from a range object, since that is immutable, but you can filter it:

julia> filter(x -> x ∉ [2,6,7,8,13,19], a)
15-element Array{Int64,1}:
  1
  3
  4
  5
  9
 10
 11
 12
 14
 15
 16
 17
 18
 20
 21

However, if a is a "real" array, you can use filter! to operate in-place.

Another solution that if often convenient is to use InvertedIndices.jl package which exports Not and you can just use indexing:

julia> r = 1:21
1:21

julia> x = [2,6,7,8,13,19]
6-element Array{Int64,1}:
  2
  6
  7
  8
 13
 19

julia> r[Not(x)]
15-element Array{Int64,1}:
  1
  3
  4
  5
  9
 10
 11
 12
 14
 15
 16
 17
 18
 20
 21
Related