add and remove
- Dart course
- Beginner
- Lesson 55/116
- 5 min
Learn list management with .add and .remove.
add and remove
To append an element to a list you use .add(); to remove one you use .remove(). names.add("Alex"); appends "Alex" to the end. names.remove("Alex"); removes the value "Alex" from the list.
Both methods mutate the original list; they do not return a new list. remove takes out the first matching element; if not found the list stays unchanged. add always appends; inserting in the middle uses insert which we will not cover here.
Mutation
.add() and .remove() change the list in place; this behavior is called mutation. For example after var names = ["Alex"]; names.add("Sam"); the names list becomes ["Alex", "Sam"]; no new list is created, the existing one grows.
Some List methods do not mutate; for example map and where return a new Iterable and leave the original list unchanged. Telling the two apart matters: mutation changes the existing one, non-mutation produces a new value.
Practice Add with add and print
Declare a List with var names = ["Alex"];. Append a new element with names.add("Sam");. Print it with print(names);. The output on a single line must be [Alex, Sam].
Starter code
// Declare names, append with add and printSample solution
var names = ["Alex"];
names.add("Sam");
print(names);Expected output
[Alex, Sam]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each method to its job
| Term | Meaning |
|---|---|
.add(x) |
Appends to the end |
.remove(x) |
Removes first match |
[i] |
Reaches i-th element |
.length |
Element count |
2 Write the add call
var names = ["Alex"];
names____;
print(names);
var names = ["Alex"];
names.add("Sam");
print(names);
Explanation: .add("Sam") appends an element to the list.
3 What does names.remove("Alex") do?
var names = ["Alex", "Sam"];
names.remove("Alex");- Adds to the list
- Removes from the list Correct answer
- Sorts the list
- Copies the list
Explanation: remove takes the first matching element out of the list.