for-in
- Dart course
- Beginner
- Lesson 45/116
- 5 min
Learn to iterate over iterables with for-in.
for-in
To walk through each element of a collection in order you use for-in: for (var x in collection) { ... }. On each iteration x takes the next element; no counter or index is needed.
In this lesson we will use a List as the example collection: the form [1, 2, 3] is a List. You will see more about Lists in the next section; for now know them as comma-separated values inside square brackets.
Iterable
for-in works with any collection of type Iterable. List is the most common iterable. for-in manages the indices itself; so an i counter variable and a length check are not needed.
for-in is especially suited to processing elements in order. If you need to skip by index or walk backwards, a classic for loop may fit better. Practical tip: pick for-in when you walk all elements from start to end.
Practice Print List elements
Declare a List with var numbers = [1, 2, 3];. Walk each element with for (var x in numbers) and print it with print(x);. The output must be 3 lines: 1, 2, 3 (one number per line).
Starter code
// Declare numbers, print each element with for-inSample solution
var numbers = [1, 2, 3];
for (var x in numbers) {
print(x);
}Expected output
1 2 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does for (var x in [1, 2, 3]) walk over?
for (var x in [1, 2, 3]) {
print(x);
}- Indices (0, 1, 2)
- Length (3)
- First element (1)
- Elements (1, 2, 3) Correct answer
Explanation: for-in walks the elements themselves, not the indices.
2 Match each part to its job
| Term | Meaning |
|---|---|
for (var x in ...) |
Walk start |
var x |
Current element |
[1, 2, 3] |
List example |
print(x) |
Prints the element |
3 Write the for-in header
var numbers = [1, 2, 3];
____ {
print(x);
}
var numbers = [1, 2, 3];
for (var x in numbers) {
print(x);
}
Explanation: for (var x in numbers) walks each element.