List access
- Dart course
- Beginner
- Lesson 54/116
- 4 min
Learn to access list elements by index.
List access
You reach List elements by index. Indexing is zero-based: the first element is list[0], the second list[1], and so on. The index is written inside square brackets.
For example in var numbers = [10, 20, 30]; the value of numbers[0] is 10, numbers[1] is 20, numbers[2] is 30. The index must be less than the list length; otherwise an error is thrown.
Index bounds
When accessing a list the index must be less than the length. The list [10, 20, 30] has 3 elements; valid indices are 0, 1, 2. Writing numbers[3] or numbers[5] throws a runtime error (RangeError).
Negative indices are not supported. You can reach the last element with numbers[numbers.length - 1] or with Dart's numbers.last property. Practical tip: in a loop use indices from 0 to length - 1.
Practice Print the second element
Declare a List with var numbers = [10, 20, 30];. Print the second element with print(numbers[1]);. The output on a single line must be 20.
Starter code
// Declare numbers, print the second elementSample solution
var numbers = [10, 20, 30];
print(numbers[1]);Expected output
20
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Get the first element
var numbers = [10, 20, 30];
print(numbers____);
var numbers = [10, 20, 30];
print(numbers[0]);
Explanation: numbers[0] gives the first element.
2 What does numbers[1] give?
var numbers = [10, 20, 30];
print(numbers[1]);- 20 Correct answer
- 30
- 10
- 1
Explanation: Indexing is zero-based; numbers[1] is the second element, 20.
3 Match each part to its job
| Term | Meaning |
|---|---|
[0] |
First element |
[1] |
Second element |
length - 1 |
Last index |
[i] |
I-th element |