remove() method is used to remove an element from the List by its name/value or index.
Let us say, we have a List that contains three names, 'Mohan', 'Kriti' and 'Salim'. And we want to remove 'Kriti' from the List.
It can be done with the 'remove()' Function
fun main() { var x = mutableListOf("Mohan", "Kriti", "Salim") x.remove("Kriti") println(x) }
So, in the above code we have created a 'List' and initialised to the variable 'x'.
Below is how the values are positioned in the List,
Next, we have used the 'remove()' function that searches for the name 'Kriti' and removes it from the List.
And we get the below output,
Let us say, we have a List that contains three names, 'Mohan', 'Kriti' and 'Salim'. And we want to remove the element at index/position '2' from the List.
So, we can use 'removeAt()' function to remove an element from the List.
Let us see the example with 'del' keyword first.
fun main() { var x = mutableListOf("Mohan", "Kriti", "Salim") x.removeAt(2) println(x) }
So, in the above code we have created a 'List' and initialised to the variable 'x'.
Below is how the values are positioned in the List,
Next, we have used the 'removeAt()' function that searches for the element at index/position '2' and removes it from the List.
And as we can see, there is 'Salim' at index/position '2'. So 'Salim' is removed from the List.
And we get the below output,