List operations
- Kotlin course
- Beginner
- Lesson 60/116
- 5 min
Learn list management with add, remove and contains.
List operations: add, remove, contains
On a mutable list the three most common methods are: add(x) appends an element, remove(x) takes out the first match, contains(x) returns a Boolean telling whether x is in the list.
val tasks = mutableListOf("Shopping", "Homework")
tasks.add("Sport")
tasks.remove("Homework")
tasks.contains("Sport") // trueadd always returns true; remove returns true if the element was found and removed, false if it was absent. So you can tell whether the operation succeeded.
Return values of contains and remove
contains(x) returns a Boolean: true if the element is in the list, false otherwise. That is why it fits easily in conditions like if (tasks.contains("Sport")).
val found = tasks.contains("Sport")
val removed = tasks.remove("Missing")
// found: true or false
// removed: false (element was absent)The Boolean return of remove is handy when you want to remove conditionally: do one thing if it succeeded, try another path if not.
Practice Add, remove and print size
Start with mutableListOf("Ava", "Liam", "Nora"). Add "Maya" to the list, remove "Liam" and print the size with println(names.size).
Starter code
fun main() {
val names = mutableListOf("Ava", "Liam", "Nora")
// Add "Maya", remove "Liam" and print size
}Sample solution
fun main() {
val names = mutableListOf("Ava", "Liam", "Nora")
names.add("Maya")
names.remove("Liam")
println(names.size)
}Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: append to the list
tasks.____("Shopping")
tasks.add("Shopping")
Explanation: tasks.add("...") appends a new task.
2 What does nums.contains(5) return?
- Int (index)
- Unit
- Boolean (true or false) Correct answer
- List<Int>
Explanation: contains returns a Boolean; true if present, false if not.
3 Match method to return value
| Term | Meaning |
|---|---|
add(x) |
true (always) |
remove(x) |
true if removed |
contains(x) |
true if present |
size |
Int |