On this page13 sections
Lecture 011: Lists
| Day | 5: Lists & Maps |
| Lecture | 011 of 057 |
| Estimated video length | 14 min |
| Target | Dart 3.12 |
| Level | Beginner |
A shopping cart, a class register, a playlist: programs constantly need to keep many values together, in order. A list is an ordered collection: one variable that holds many values, each at a numbered position.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 006–010: variables, data types, final / const, strings and null safety.
Learning Objectives
- Create a list, with or without a type
- Read and change items by their index
- Add, insert and remove items
- Search a list with
containsandindexOf - Sort, reverse, slice and join a list
- Combine lists with
+and the spread operator...
1. Creating a List
Put the values in square brackets, separated by commas:
var fruits = ['apple', 'banana', 'mango'];
List<int> marks = [85, 92, 78];
var empty = <String>[];
print(fruits); // [apple, banana, mango]
print(marks); // [85, 92, 78]
print(empty); // []List<int> means "a list of ints". With var, Dart works the type out from the values.
For an empty list, say the type in front of the brackets: <String>[].
2. Index: Positions Start at 0
Each item has an index. The first item is at index 0, not 1:
fruits → [ 'apple', 'banana', 'mango' ]
index 0 1 2print(fruits[0]); // apple
print(fruits[2]); // mango
print(fruits.length); // 3
print(fruits.first); // apple
print(fruits.last); // mango
fruits[1] = 'orange'; // change the item at index 1
print(fruits); // [apple, orange, mango]The last index is always length - 1.
3. Adding and Removing
fruits.add('grapes'); // to the end
fruits.addAll(['kiwi', 'peach']); // several at once
print(fruits); // [apple, orange, mango, grapes, kiwi, peach]
fruits.insert(0, 'cherry'); // at a position
print(fruits); // [cherry, apple, orange, mango, grapes, kiwi, peach]
fruits.remove('kiwi'); // by value
fruits.removeAt(0); // by index
var lastOne = fruits.removeLast(); // removes and gives it back
print(lastOne); // peach
print(fruits); // [apple, orange, mango, grapes]4. Searching
print(fruits.contains('mango')); // true
print(fruits.indexOf('mango')); // 2
print(fruits.indexOf('melon')); // -1 (not found)
print(fruits.isEmpty); // false5. Sorting and Other Tools
var numbers = [40, 10, 30, 20];
numbers.sort();
print(numbers); // [10, 20, 30, 40]
print(numbers.reversed.toList()); // [40, 30, 20, 10]
print(numbers.sublist(1, 3)); // [20, 30] (index 1 up to, not including, 3)
print(numbers.join(' - ')); // 10 - 20 - 30 - 40| Tool | Does |
|---|---|
length, first, last | size and the ends |
add(x), addAll(list), insert(i, x) | add items |
remove(x), removeAt(i), removeLast(), clear() | remove items |
contains(x), indexOf(x) | search |
sort(), reversed, sublist(a, b), join(sep) | rearrange and convert |
6. Combining Lists
var a = [1, 2];
var b = [3, 4];
print(a + b); // [1, 2, 3, 4]
print([...a, 0, ...b]); // [1, 2, 0, 3, 4]... (the spread operator) unpacks a list's items into another list.
Code Examples
Example 1: A Shopping Cart
void main() {
var cart = ['Milk', 'Bread', 'Eggs'];
print('Cart: $cart (${cart.length} items)');
cart.add('Butter');
cart.remove('Bread');
cart.insert(0, 'Tea');
print('Updated: $cart');
print('First item: ${cart.first}');
print('Has eggs? ${cart.contains('Eggs')}');
cart.sort();
print('Sorted: ${cart.join(', ')}');
}Output
Cart: [Milk, Bread, Eggs] (3 items)
Updated: [Tea, Milk, Eggs, Butter]
First item: Tea
Has eggs? true
Sorted: Butter, Eggs, Milk, TeaCommon Beginner Mistakes
1. Using an index that doesn't exist
var fruits = ['apple', 'banana', 'mango'];
print(fruits[3]);Unhandled exception:
RangeError (length): Invalid value: Not in inclusive range 0..2: 3Three items means indexes 0, 1, 2. The last one is fruits[fruits.length - 1].
2. Adding the wrong type
List<int> marks = [85, 92];
marks.add('A+');Error: The argument type 'String' can't be assigned to the parameter type 'int'.3. Changing a const list
const days = ['Mon', 'Tue'];
days.add('Wed');Unhandled exception:
Unsupported operation: Cannot add to an unmodifiable listA const list can never change (Lecture 008). Use var or final if it needs to grow.
4. Expecting sort() to give back a new list: sort() changes the list itself and returns
nothing, so var sorted = numbers.sort(); is wrong. Call numbers.sort();, then use numbers.
Practice Questions
- In
var colors = ['red', 'green', 'blue'];, what iscolors[1]? - What is the index of the last item in a list of 10 items?
- After
var n = [3, 1, 2]; n.sort();, what isn? - What does
['a', 'b'].indexOf('z')give? - Write one line that puts
0at the start of a list calledscores. - What does
[...[1, 2], ...[3]]give?
Practice Answers
green9[1, 2, 3]-1scores.insert(0, 0);[1, 2, 3]
Key Takeaways
- A list keeps values in order:
['a', 'b'], typed asList<String>. - Indexes start at
0; the last islength - 1. add,insert,remove,removeAtchange the list.containsandindexOfsearch it;sort,reversed,sublist,joinrearrange it.+and...combine lists.