In this tutorial, we’ll see how we can remove an element from a Scala List by index.
2. Remove an Item by Index From a List
Here’s the list we’ll be working with:
scala> val lst = List('a', 'b', 'c', 'd', 'e') val lst: List[Char] = List(a, b, c, d, e)
There are multiple ways to remove an element by index from a List. Let’s see how we can remove the element at index 2 using different approaches.
2.1. Using the filter() Method
The first solution we’ll look at is a naive approach. Given a List, we can manually filter the item. If we want to filter by index, then zipWithFilter is very useful:
scala> lst.zipWithIndex.filter(_._2 != 2).map(_._1) val res0: List[Char] = List(a, b, d, e)
We start by adding the index to the list, then exclude index 2. Finally, we remove the indexes to get back to the original structure.
2.2. Using the splitAt() Method
While the previous approach worked just fine, it’s a bit complex and had too much boilerplate. Fortunately, Scala offers some methods that we can use. One such method is splitAt():
scala> val (first, second) = lst.splitAt(2) val first: List[Char] = List(a, b) val second: List[Char] = List(c, d, e) scala> first ++ second.tail val res2: List[Char] = List(a, b, d, e)
This approach starts by splitting the original list into two. The list is split at index 2. So we have a sub-list with the first two elements and another with the remaining. Since the element at index 2 is still included in the second sub-list, we remove it when we merge the sub-lists again.
While we don’t need to be adding some custom logic using map() and filter(), there’s still room for improvement to our solution.
2.3. Using the patch() Method
The final approach is to make use of the patch() method. This method can be used to replace a sub-sequence of a List.
We can also use it to remove elements, by “replacing” the sub-sequence with an empty one:
scala> lst.patch(2, List.empty, 1) val res3: List[Char] = List(a, b, d, e) scala> lst.patch(2, Nil, 1) val res4: List[Char] = List(a, b, d, e)
We should note that we can use the List.empty() method to be explicit or use Nil for simplicity.
In this article, we saw how to remove a given element by index from a Scala List.