Delete multiple elements from a list

Viewed 1885

Given this list:

list = [1,2,3,4,5]

how can I return a new list that has these elements?

[3,4,5]

I know I use List.delete/2 but as for as I can tell that will only delete 1 element at a time. I want to remove the first two elements in one fell swoop.

4 Answers

I think you are looking for this

# Example with static values
iex> [1, 2, 3, 4, 5] -- [1, 2]
[3, 4, 5]

# Example with Enum.drop/2, with multiple values
iex> Enum.drop([1, 2, 3, 4, 5], 2)
[3, 4, 5]
iex> Enum.drop([1, 2, 3, 4, 5], -2)
[1, 2, 3]
iex> Enum.drop([1, 2, 3, 4, 5], 20)
[]
iex> Enum.drop([1, 2, 3, 4, 5], -20)
[]

You can use List.delete/2 only can delete one at time and Enum.drop/2 can delete multiple depend how you use it.

If you want to remove elements based on some arbitrary condition, you can use Enum.reject/2, and provide the reject condition as an argument.

iex(1)> Enum.reject([1,2,3,4,5], fn x -> x in [1,2] end)
[3, 4, 5]

To withdraw only first 2 elements: you can pattern match like that:

[_,_|sublist] = list

you can also use tl/1 twice:

list |> tl() |> tl ()

However this last solution does not do it in one fell swoop.

If the number of elements to drop varies, I do not see another solution that the one @Dogbert suggested: to use Enum.drop/2, or also Enum.split/2 like that:

{_,sublist} = Enum.split(list,2)

Another approach, which could be dynamic based on your implementation is Enum.filter/2

It would look something like this:

Enum.filter(list, &(&1 >= 3))

=> [3,4,5]
Related