On this page24 sections
- Prerequisites
- Connection With Previous Lectures
- Learning Objectives
- 1. sort — Putting a List in Order
- 2. sort Returns Nothing
- 3. Sorting Strings
- 4. compareTo — Which Comes First?
- 5. A Comparator Function
- 6. Descending Order
- 7. Sorting Strings Without Caring About Case
- 8. Sorting by Length
- 9. Keeping the Original Order
- 10. reversed — Back to Front
- 11. shuffle — Random Order
- 12. A Real-World Example
- Code Examples
- Common Beginner Mistakes
- Best Practices
- Mini Challenge
- Practice Questions
- Practice Answers
- Quick Revision
- Key Takeaways
- What's Next?
Lecture 45 — Sorting & Reversing Lists
| Category | 7 — Lists |
| Lecture | 045 of 140 |
| Estimated video length | 8 min |
| Target | Dart 3.12.2 |
| Level | Beginner |
A list keeps elements in the order they arrived. With
sortandreversed, you put them in the order you need — smallest first, A to Z, longest first, or back to front.
Contents
Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways
Every error message in this lecture is real. Each one was produced by running the code shown on Dart 3.12.2, so you will recognize it when you meet it yourself.
Prerequisites
Students should already understand, from Lectures 001–044:
toLowerCase()andlengthon strings (Lecture 008)- comparison operators
<,>,==(Lecture 018) - arrow and anonymous functions (Lecture 034)
- creating lists, indexes,
firstandlast(Lectures 039–040) add,remove, and whyaddreturns nothing (Lecture 041)- turning a result into a list with
toList()(Lecture 043)
Connection With Previous Lectures
In Lecture 018 we compared strings with == — but == only says equal or not equal. It
cannot say whether 'Ali' comes before 'Sara', so we postponed alphabetical order until now.
Numbers have the same problem at list scale: given [72, 95, 64, 88], we can add them up
(Lecture 044), but we cannot yet show them as a ranking. Every leaderboard, price list and
contact book needs its elements in order.
Learning Objectives
By the end of this lecture you will be able to:
- Sort a list of numbers or strings with
sort() - Explain why
sort()changes the list and returns nothing - Use
compareToto compare two values - Write a comparator
(a, b) => a.compareTo(b)and flip it for descending order - Sort strings without caring about capital letters
- Sort by something other than the value itself, such as length
- Keep the original order by sorting a copy
- Reverse a list with
reversed, and shuffle one withshuffle()
1. sort — Putting a List in Order
sort() rearranges a list's elements from smallest to largest.
Analogy — think of tidying a bookshelf. You don't buy a second shelf; you move the books on the shelf you have until they stand in order.
void main() {
var marks = [72, 95, 64, 88];
marks.sort();
print(marks);
}[64, 72, 88, 95]Like the bookshelf, sort works in place: marks itself is rearranged. No new list is
created.
2. sort Returns Nothing
Because sort changes the list it is called on, it has nothing to give back — exactly like
add in Lecture 041. Trying to use its result fails before the program runs:
void main() {
var marks = [72, 95, 64, 88];
print(marks.sort()); // ✗ sort returns void
}Error: This expression has type 'void' and can't be used.
print(marks.sort()); // ✗ sort returns void
^Saving it first, as in var sorted = marks.sort();, only moves the same error to the line
that uses sorted. Sort on one line, then use the list on the next.
3. Sorting Strings
Strings sort in alphabetical order:
void main() {
var names = ['Sara', 'Zayan', 'Ali', 'Hina'];
names.sort();
print(names);
}[Ali, Hina, Sara, Zayan]But watch what happens when the capitals are mixed:
void main() {
var names = ['sara', 'Zayan', 'ali'];
names.sort();
print(names);
}[Zayan, ali, sara]Dart compares the character codes of the letters, and every capital letter comes before
every small letter. So 'Z' beats 'a'. Section 7 fixes this.
4. compareTo — Which Comes First?
a.compareTo(b) answers the question == cannot: which of the two comes first? It returns a
negative number if a comes first, zero if they are equal, and a positive number if
b comes first.
void main() {
print('Ali'.compareTo('Sara'));
print('Sara'.compareTo('Ali'));
print('Ali'.compareTo('Ali'));
print(5.compareTo(3));
}-1
1
0
1Only the sign matters — negative, zero or positive — not the exact number.
5. A Comparator Function
sort accepts a function that takes two elements and returns that same kind of number. This
function is called a comparator. Writing a.compareTo(b) gives the normal order:
void main() {
var prices = [450, 120, 800, 300];
prices.sort((a, b) => a.compareTo(b));
print(prices);
}[120, 300, 450, 800]Dart calls the comparator for pairs of elements and places a before b whenever the answer
is negative. With no comparator, sort() does exactly this.
6. Descending Order
To sort largest first, swap a and b in the comparator:
void main() {
var marks = [72, 95, 64, 88];
marks.sort((a, b) => b.compareTo(a));
print(marks);
}[95, 88, 72, 64]Every answer flips its sign, so the whole order flips. The same trick sorts names Z to A.
7. Sorting Strings Without Caring About Case
To put 'ali' and 'Zayan' in the order a person expects, compare lowercase copies of
both strings:
void main() {
var names = ['sara', 'Zayan', 'ali'];
names.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
print(names);
}[ali, sara, Zayan]toLowerCase() is used only for the comparison. The elements themselves keep their original
spelling.
8. Sorting by Length
A comparator can compare anything about the elements. Here the names are compared by their
length, which is an int:
void main() {
var words = ['banana', 'fig', 'apple', 'kiwis'];
words.sort((a, b) => a.length.compareTo(b.length));
print(words);
}[fig, apple, kiwis, banana]'kiwis' and 'apple' both have five letters. When two elements compare as equal, Dart does
not promise which of them comes first — so don't rely on the order of ties.
9. Keeping the Original Order
Sometimes you need the sorted version and the original. Simply giving the list a second name does not help — both names point at the same list:
void main() {
var marks = [72, 95, 64];
var sorted = marks;
sorted.sort();
print(marks);
}[64, 72, 95]Make a real copy with List.of(...) or toList(), and sort the copy:
void main() {
var marks = [72, 95, 64];
var sorted = List.of(marks);
sorted.sort();
print('Original: $marks');
print('Sorted: $sorted');
}Original: [72, 95, 64]
Sorted: [64, 72, 95]var sorted = marks.toList(); works just as well. A shorter way to copy lists, the spread
operator, comes in Lecture 046 — Collection Features.
10. reversed — Back to Front
reversed gives the elements in the opposite order. It does not change the list:
void main() {
var steps = ['wake', 'eat', 'study'];
print(steps.reversed);
print(steps);
}(study, eat, wake)
[wake, eat, study]Notice the round brackets. reversed is not a List but an Iterable — a sequence you can
loop over, but not index or sort. Add .toList() to get a real list:
void main() {
var steps = ['wake', 'eat', 'study'];
var backwards = steps.reversed.toList();
print(backwards);
print(backwards[0]);
}[study, eat, wake]
studyWe will study Iterable properly in Lecture 046 — Collection Features. Note that reversed
only flips the current order — it does not sort. Sort first, then reverse, for largest first.
11. shuffle — Random Order
shuffle() is the opposite of sorting: it puts the elements in a random order, in place. Like
sort, it returns nothing.
void main() {
var players = ['Ali', 'Sara', 'Zayan', 'Hina'];
players.shuffle();
print(players);
}One run printed:
[Hina, Sara, Zayan, Ali]Your output will almost certainly differ — that is the point. Use it for quiz questions or picking teams.
12. A Real-World Example
void main() {
var students = ['sara', 'Ali', 'zayan', 'Hina'];
var marks = [72, 95, 64, 88];
var ranking = List.of(marks);
ranking.sort((a, b) => b.compareTo(a));
students.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
print('Class list: $students');
print('Ranking: $ranking');
print('Top mark: ${ranking.first}');
print('Entry order: $marks');
print('Lowest to highest: ${ranking.reversed.toList()}');
}Class list: [Ali, Hina, sara, zayan]
Ranking: [95, 88, 72, 64]
Top mark: 95
Entry order: [72, 95, 64, 88]
Lowest to highest: [64, 72, 88, 95]The class list is sorted A to Z regardless of capitals. The marks are copied before sorting,
so the entry order survives, and reversed turns the ranking into lowest-first without a
second sort.
Code Examples
Example 1 — Numbers Smallest First
void main() {
var ages = [30, 18, 45, 21];
ages.sort();
print(ages);
}[18, 21, 30, 45]Example 2 — Names A to Z
void main() {
var cities = ['Lahore', 'Karachi', 'Quetta', 'Islamabad'];
cities.sort();
print(cities);
}[Islamabad, Karachi, Lahore, Quetta]Example 3 — Names Z to A
void main() {
var names = ['Ali', 'Sara', 'Zayan'];
names.sort((a, b) => b.compareTo(a));
print(names);
}[Zayan, Sara, Ali]Example 4 — Ignoring Capitals
void main() {
var fruits = ['mango', 'Apple', 'banana', 'Cherry'];
fruits.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
print(fruits);
}[Apple, banana, Cherry, mango]Example 5 — Longest Word First
void main() {
var words = ['to', 'dart', 'learn', 'we'];
words.sort((a, b) => b.length.compareTo(a.length));
print(words.first);
}learnExample 6 — A Countdown
void main() {
var numbers = [1, 2, 3, 4, 5];
for (final n in numbers.reversed) {
print(n);
}
}5
4
3
2
1A for-in loop can walk an Iterable directly — no toList() needed.
Example 7 — Student Marks: Highest and Lowest
void main() {
final marks = [67, 91, 54, 78, 85];
var sorted = List.of(marks);
sorted.sort();
print('Lowest: ${sorted.first}');
print('Highest: ${sorted.last}');
print('As entered: $marks');
}Lowest: 54
Highest: 91
As entered: [67, 91, 54, 78, 85]How it works
List.of(marks)copies the list, so sorting does not disturb the entry order.- After an ascending sort,
firstis the smallest andlastthe largest.
Example 8 — Shopping: Cheapest First
void main() {
final prices = [1200, 450, 3000, 800];
prices.sort((a, b) => a.compareTo(b));
print('Cheapest first: $prices');
print('Most expensive: ${prices.last}');
}Cheapest first: [450, 800, 1200, 3000]
Most expensive: 3000How it works
a.compareTo(b)is the normal ascending order — the same assort()with no comparator.- A
finallist can be sorted: the variable does not change, only the order inside.
Example 9 — Bank Balance: Biggest Transactions First
void main() {
var deposits = [500.0, 2500.0, 150.0, 1000.0];
deposits.sort((a, b) => b.compareTo(a));
print('Largest first: $deposits');
print('Top two: ${deposits[0]}, ${deposits[1]}');
}Largest first: [2500.0, 1000.0, 500.0, 150.0]
Top two: 2500.0, 1000.0How it works
b.compareTo(a)flips the order, so the biggest deposit lands at index0.compareToworks ondoubleexactly as onint.
Example 10 — Temperature: The Middle Reading
void main() {
var temps = [24.5, 19.0, 31.0, 22.0, 27.5];
var sorted = temps.toList();
sorted.sort();
print('Sorted: $sorted');
print('Middle: ${sorted[sorted.length ~/ 2]}');
}Sorted: [19.0, 22.0, 24.5, 27.5, 31.0]
Middle: 24.5How it works
toList()makes the copy this time; it behaves likeList.of.- With five sorted readings, index
5 ~/ 2— that is2— holds the middle one.
Common Beginner Mistakes
1. Using the result of sort
void main() {
var marks = [72, 95, 64];
// print(marks.sort()); // ✗
}Error: This expression has type 'void' and can't be used.Call marks.sort(); on its own line, then print(marks);.
2. Returning a bool from the comparator
void main() {
var marks = [72, 95, 64];
// marks.sort((a, b) => a > b); // ✗
}Error: A value of type 'bool' can't be returned from a function with return type 'int'.A comparator returns a negative, zero or positive int. Use a.compareTo(b).
3. Expecting 'Zayan' after 'ali'
Plain sort() puts every capital letter first. Compare toLowerCase() copies when people's
eyes, not character codes, decide the order.
4. Sorting the "copy" that is not a copy
var sorted = marks; gives the same list a second name. Sorting sorted also sorts marks.
Use List.of(marks) or marks.toList().
5. Treating reversed as a list
void main() {
var marks = [72, 95, 64];
// List<int> backwards = marks.reversed; // ✗
// marks.reversed.sort(); // ✗
}Error: A value of type 'Iterable<int>' can't be assigned to a variable of type 'List<int>'.
Error: The method 'sort' isn't defined for the type 'Iterable<int>'.Add .toList(): marks.reversed.toList().
6. Expecting reversed to sort
[3, 1, 2].reversed gives (2, 1, 3) — the same elements, back to front. Sort first if you
want largest first, or use b.compareTo(a).
7. Sorting a const list
void main() {
const marks = [72, 95, 64];
marks.sort(); // ✗ const list
}Unhandled exception:
Unsupported operation: Cannot modify an unmodifiable listA const list can never change, not even its order. Sort a List.of copy instead.
Best Practices
- Call
sort()on its own line; never use its result. - Use
sort()with no comparator for plain ascending order, andb.compareTo(a)for descending. - Compare
toLowerCase()copies when sorting names that people typed. - Sort a
List.ofcopy when the original order still matters. - Use
reverseddirectly in afor-inloop; add.toList()only when you need a list. - Don't rely on the order of elements that compare as equal.
Mini Challenge
Sort the guest list ['sara', 'Ali', 'hina', 'Zayan'] from A to Z without caring about
capitals, then print it, and print it again from Z to A using reversed.
[Ali, hina, sara, Zayan]
[Zayan, sara, hina, Ali]Try it yourself before opening the solution.
Show solution
void main() {
var guests = ['sara', 'Ali', 'hina', 'Zayan'];
guests.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
print(guests);
print(guests.reversed.toList());
}[Ali, hina, sara, Zayan]
[Zayan, sara, hina, Ali]Practice Questions
Work through these in order — they run from beginner to application to challenge.
Beginner
- Sort
[9, 2, 7, 4]and print it. - Sort
['Sara', 'Ali', 'Zayan']and print it. - Print
[1, 2, 3]back to front as a list.
Application
- Sort
[40, 10, 30, 20]from largest to smallest and print it. - Print what
'apple'.compareTo('banana'),'pear'.compareTo('fig')and7.compareTo(7)return, each on its own line. - Sort
['Dart', 'flutter', 'Code']without caring about capitals and print it. - Sort
['elephant', 'cat', 'horse']from shortest to longest and print it. - Start with
final prices = [300, 100, 200]. Print a sorted copy, then printpricesto show it is unchanged.
Challenge
- Given
[58, 92, 75, 81, 66], print the top three marks, highest first, as a list. - Given
['Hina', 'ali', 'Sara', 'zayan'], sort the names Z to A without caring about capitals, then print the list and the name that comes last alphabetically.
Practice Answers
Question 1 — Solution
void main() {
var numbers = [9, 2, 7, 4];
numbers.sort();
print(numbers);
}[2, 4, 7, 9]Question 2 — Solution
void main() {
var names = ['Sara', 'Ali', 'Zayan'];
names.sort();
print(names);
}[Ali, Sara, Zayan]Question 3 — Solution
void main() {
var numbers = [1, 2, 3];
print(numbers.reversed.toList());
}[3, 2, 1]Question 4 — Solution
void main() {
var numbers = [40, 10, 30, 20];
numbers.sort((a, b) => b.compareTo(a));
print(numbers);
}[40, 30, 20, 10]Question 5 — Solution
void main() {
print('apple'.compareTo('banana'));
print('pear'.compareTo('fig'));
print(7.compareTo(7));
}-1
1
0Question 6 — Solution
void main() {
var words = ['Dart', 'flutter', 'Code'];
words.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
print(words);
}[Code, Dart, flutter]Question 7 — Solution
void main() {
var animals = ['elephant', 'cat', 'horse'];
animals.sort((a, b) => a.length.compareTo(b.length));
print(animals);
}[cat, horse, elephant]Question 8 — Solution
void main() {
final prices = [300, 100, 200];
var sorted = List.of(prices);
sorted.sort();
print(sorted);
print(prices);
}[100, 200, 300]
[300, 100, 200]Question 9 — Solution
void main() {
var marks = [58, 92, 75, 81, 66];
marks.sort((a, b) => b.compareTo(a));
var top = [marks[0], marks[1], marks[2]];
print(top);
}[92, 81, 75]A shorter way to take the first few elements of a list comes in Lecture 046.
Question 10 — Solution
void main() {
var names = ['Hina', 'ali', 'Sara', 'zayan'];
names.sort((a, b) => b.toLowerCase().compareTo(a.toLowerCase()));
print(names);
print('Last alphabetically: ${names.first}');
}[zayan, Sara, Hina, ali]
Last alphabetically: zayanSorted Z to A, the name that comes last in the alphabet is at the front, so it is first.
Quick Revision
- Does
sort()create a new list or change the existing one? - Why does
var s = list.sort();fail? - What do negative, zero and positive results from
compareTomean? - How do you turn an ascending comparator into a descending one?
- Why does
'Zayan'come before'ali'with plainsort()? - How do you keep the original order while getting a sorted version?
- Why does
print(list.reversed)show round brackets? - What does
shuffle()do, and what does it return?
Key Takeaways
sort()orders a list in place, smallest first, and returnsvoid.a.compareTo(b)is negative, zero or positive — and only the sign matters.- A comparator
(a, b) => a.compareTo(b)sorts ascending;b.compareTo(a)sorts descending. - Plain string sorting puts all capitals first; compare
toLowerCase()copies to ignore case. - A comparator can compare any property, such as
length; ties have no guaranteed order. var b = a;is not a copy — useList.of(a)ora.toList()before sorting.reversedis anIterablethat leaves the list unchanged;.toList()makes it a list.shuffle()puts a list in random order, in place.
What's Next?
Lecture 46 — Collection Features. We have been copying lists with List.of, meeting
Iterable without studying it, and collecting the "first few" elements by hand. Next we will
learn the features that make building lists smoother: the spread operator, collection if
and for, unmodifiable lists, and what an Iterable really is.