On this page13 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Creating a List
  4. 2. Index: Positions Start at 0
  5. 3. Adding and Removing
  6. 4. Searching
  7. 5. Sorting and Other Tools
  8. 6. Combining Lists
  9. Code Examples
  10. Common Beginner Mistakes
  11. Practice Questions
  12. Practice Answers
  13. Key Takeaways

Lecture 011: Lists

Day5: Lists & Maps
Lecture011 of 057
Estimated video length14 min
TargetDart 3.12
LevelBeginner

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 contains and indexOf
  • 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:

dart
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:

code
fruits →  [ 'apple', 'banana', 'mango' ]
index        0          1         2
dart
print(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

dart
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

dart
print(fruits.contains('mango'));  // true
print(fruits.indexOf('mango'));   // 2
print(fruits.indexOf('melon'));   // -1 (not found)
print(fruits.isEmpty);            // false

5. Sorting and Other Tools

dart
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
ToolDoes
length, first, lastsize 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

dart
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

dart
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

code
Cart: [Milk, Bread, Eggs] (3 items)
Updated: [Tea, Milk, Eggs, Butter]
First item: Tea
Has eggs? true
Sorted: Butter, Eggs, Milk, Tea

Common Beginner Mistakes

1. Using an index that doesn't exist

dart
var fruits = ['apple', 'banana', 'mango'];
print(fruits[3]);
code
Unhandled exception:
RangeError (length): Invalid value: Not in inclusive range 0..2: 3

Three items means indexes 0, 1, 2. The last one is fruits[fruits.length - 1].

2. Adding the wrong type

dart
List<int> marks = [85, 92];
marks.add('A+');
code
Error: The argument type 'String' can't be assigned to the parameter type 'int'.

3. Changing a const list

dart
const days = ['Mon', 'Tue'];
days.add('Wed');
code
Unhandled exception:
Unsupported operation: Cannot add to an unmodifiable list

A 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

  1. In var colors = ['red', 'green', 'blue'];, what is colors[1]?
  2. What is the index of the last item in a list of 10 items?
  3. After var n = [3, 1, 2]; n.sort();, what is n?
  4. What does ['a', 'b'].indexOf('z') give?
  5. Write one line that puts 0 at the start of a list called scores.
  6. What does [...[1, 2], ...[3]] give?

Practice Answers

  1. green
  2. 9
  3. [1, 2, 3]
  4. -1
  5. scores.insert(0, 0);
  6. [1, 2, 3]

Key Takeaways

  • A list keeps values in order: ['a', 'b'], typed as List<String>.
  • Indexes start at 0; the last is length - 1.
  • add, insert, remove, removeAt change the list.
  • contains and indexOf search it; sort, reversed, sublist, join rearrange it.
  • + and ... combine lists.