Watch the video (8 min)
On this page24 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. sort — Putting a List in Order
  5. 2. sort Returns Nothing
  6. 3. Sorting Strings
  7. 4. compareTo — Which Comes First?
  8. 5. A Comparator Function
  9. 6. Descending Order
  10. 7. Sorting Strings Without Caring About Case
  11. 8. Sorting by Length
  12. 9. Keeping the Original Order
  13. 10. reversed — Back to Front
  14. 11. shuffle — Random Order
  15. 12. A Real-World Example
  16. Code Examples
  17. Common Beginner Mistakes
  18. Best Practices
  19. Mini Challenge
  20. Practice Questions
  21. Practice Answers
  22. Quick Revision
  23. Key Takeaways
  24. What's Next?

Lecture 45 — Sorting & Reversing Lists

Category7 — Lists
Lecture045 of 140
Estimated video length8 min
TargetDart 3.12.2
LevelBeginner

A list keeps elements in the order they arrived. With sort and reversed, 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() and length on strings (Lecture 008)
  • comparison operators <, >, == (Lecture 018)
  • arrow and anonymous functions (Lecture 034)
  • creating lists, indexes, first and last (Lectures 039–040)
  • add, remove, and why add returns 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 compareTo to 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 with shuffle()

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.

dart
void main() {
  var marks = [72, 95, 64, 88];
  marks.sort();
  print(marks);
}
output
[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:

dart
void main() {
  var marks = [72, 95, 64, 88];
  print(marks.sort()); // ✗ sort returns void
}
output
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:

dart
void main() {
  var names = ['Sara', 'Zayan', 'Ali', 'Hina'];
  names.sort();
  print(names);
}
output
[Ali, Hina, Sara, Zayan]

But watch what happens when the capitals are mixed:

dart
void main() {
  var names = ['sara', 'Zayan', 'ali'];
  names.sort();
  print(names);
}
output
[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.

dart
void main() {
  print('Ali'.compareTo('Sara'));
  print('Sara'.compareTo('Ali'));
  print('Ali'.compareTo('Ali'));
  print(5.compareTo(3));
}
output
-1
1
0
1

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

dart
void main() {
  var prices = [450, 120, 800, 300];
  prices.sort((a, b) => a.compareTo(b));
  print(prices);
}
output
[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:

dart
void main() {
  var marks = [72, 95, 64, 88];
  marks.sort((a, b) => b.compareTo(a));
  print(marks);
}
output
[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:

dart
void main() {
  var names = ['sara', 'Zayan', 'ali'];
  names.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
  print(names);
}
output
[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:

dart
void main() {
  var words = ['banana', 'fig', 'apple', 'kiwis'];
  words.sort((a, b) => a.length.compareTo(b.length));
  print(words);
}
output
[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:

dart
void main() {
  var marks = [72, 95, 64];
  var sorted = marks;
  sorted.sort();
  print(marks);
}
output
[64, 72, 95]

Make a real copy with List.of(...) or toList(), and sort the copy:

dart
void main() {
  var marks = [72, 95, 64];
  var sorted = List.of(marks);
  sorted.sort();
  print('Original: $marks');
  print('Sorted: $sorted');
}
output
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:

dart
void main() {
  var steps = ['wake', 'eat', 'study'];
  print(steps.reversed);
  print(steps);
}
output
(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:

dart
void main() {
  var steps = ['wake', 'eat', 'study'];
  var backwards = steps.reversed.toList();
  print(backwards);
  print(backwards[0]);
}
output
[study, eat, wake]
study

We 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.

dart
void main() {
  var players = ['Ali', 'Sara', 'Zayan', 'Hina'];
  players.shuffle();
  print(players);
}

One run printed:

output
[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

dart
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()}');
}
output
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

dart
void main() {
  var ages = [30, 18, 45, 21];
  ages.sort();
  print(ages);
}
output
[18, 21, 30, 45]

Example 2 — Names A to Z

dart
void main() {
  var cities = ['Lahore', 'Karachi', 'Quetta', 'Islamabad'];
  cities.sort();
  print(cities);
}
output
[Islamabad, Karachi, Lahore, Quetta]

Example 3 — Names Z to A

dart
void main() {
  var names = ['Ali', 'Sara', 'Zayan'];
  names.sort((a, b) => b.compareTo(a));
  print(names);
}
output
[Zayan, Sara, Ali]

Example 4 — Ignoring Capitals

dart
void main() {
  var fruits = ['mango', 'Apple', 'banana', 'Cherry'];
  fruits.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
  print(fruits);
}
output
[Apple, banana, Cherry, mango]

Example 5 — Longest Word First

dart
void main() {
  var words = ['to', 'dart', 'learn', 'we'];
  words.sort((a, b) => b.length.compareTo(a.length));
  print(words.first);
}
output
learn

Example 6 — A Countdown

dart
void main() {
  var numbers = [1, 2, 3, 4, 5];
  for (final n in numbers.reversed) {
    print(n);
  }
}
output
5
4
3
2
1

A for-in loop can walk an Iterable directly — no toList() needed.

Example 7 — Student Marks: Highest and Lowest

dart
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');
}
output
Lowest: 54
Highest: 91
As entered: [67, 91, 54, 78, 85]

How it works

  1. List.of(marks) copies the list, so sorting does not disturb the entry order.
  2. After an ascending sort, first is the smallest and last the largest.

Example 8 — Shopping: Cheapest First

dart
void main() {
  final prices = [1200, 450, 3000, 800];
  prices.sort((a, b) => a.compareTo(b));
  print('Cheapest first: $prices');
  print('Most expensive: ${prices.last}');
}
output
Cheapest first: [450, 800, 1200, 3000]
Most expensive: 3000

How it works

  1. a.compareTo(b) is the normal ascending order — the same as sort() with no comparator.
  2. A final list can be sorted: the variable does not change, only the order inside.

Example 9 — Bank Balance: Biggest Transactions First

dart
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]}');
}
output
Largest first: [2500.0, 1000.0, 500.0, 150.0]
Top two: 2500.0, 1000.0

How it works

  1. b.compareTo(a) flips the order, so the biggest deposit lands at index 0.
  2. compareTo works on double exactly as on int.

Example 10 — Temperature: The Middle Reading

dart
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]}');
}
output
Sorted: [19.0, 22.0, 24.5, 27.5, 31.0]
Middle: 24.5

How it works

  1. toList() makes the copy this time; it behaves like List.of.
  2. With five sorted readings, index 5 ~/ 2 — that is 2 — holds the middle one.

Common Beginner Mistakes

1. Using the result of sort

dart
void main() {
  var marks = [72, 95, 64];
  // print(marks.sort()); // ✗
}
output
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

dart
void main() {
  var marks = [72, 95, 64];
  // marks.sort((a, b) => a > b); // ✗
}
output
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

dart
void main() {
  var marks = [72, 95, 64];
  // List<int> backwards = marks.reversed; // ✗
  // marks.reversed.sort(); // ✗
}
output
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

dart
void main() {
  const marks = [72, 95, 64];
  marks.sort(); // ✗ const list
}
output
Unhandled exception:
Unsupported operation: Cannot modify an unmodifiable list

A 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, and b.compareTo(a) for descending.
  • Compare toLowerCase() copies when sorting names that people typed.
  • Sort a List.of copy when the original order still matters.
  • Use reversed directly in a for-in loop; 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.

output
[Ali, hina, sara, Zayan]
[Zayan, sara, hina, Ali]

Try it yourself before opening the solution.

Show solution
dart
void main() {
  var guests = ['sara', 'Ali', 'hina', 'Zayan'];
  guests.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
  print(guests);
  print(guests.reversed.toList());
}
output
[Ali, hina, sara, Zayan]
[Zayan, sara, hina, Ali]

Practice Questions

Work through these in order — they run from beginner to application to challenge.

Beginner

  1. Sort [9, 2, 7, 4] and print it.
  2. Sort ['Sara', 'Ali', 'Zayan'] and print it.
  3. Print [1, 2, 3] back to front as a list.

Application

  1. Sort [40, 10, 30, 20] from largest to smallest and print it.
  2. Print what 'apple'.compareTo('banana'), 'pear'.compareTo('fig') and 7.compareTo(7) return, each on its own line.
  3. Sort ['Dart', 'flutter', 'Code'] without caring about capitals and print it.
  4. Sort ['elephant', 'cat', 'horse'] from shortest to longest and print it.
  5. Start with final prices = [300, 100, 200]. Print a sorted copy, then print prices to show it is unchanged.

Challenge

  1. Given [58, 92, 75, 81, 66], print the top three marks, highest first, as a list.
  2. 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

dart
void main() {
  var numbers = [9, 2, 7, 4];
  numbers.sort();
  print(numbers);
}
output
[2, 4, 7, 9]

Question 2 — Solution

dart
void main() {
  var names = ['Sara', 'Ali', 'Zayan'];
  names.sort();
  print(names);
}
output
[Ali, Sara, Zayan]

Question 3 — Solution

dart
void main() {
  var numbers = [1, 2, 3];
  print(numbers.reversed.toList());
}
output
[3, 2, 1]

Question 4 — Solution

dart
void main() {
  var numbers = [40, 10, 30, 20];
  numbers.sort((a, b) => b.compareTo(a));
  print(numbers);
}
output
[40, 30, 20, 10]

Question 5 — Solution

dart
void main() {
  print('apple'.compareTo('banana'));
  print('pear'.compareTo('fig'));
  print(7.compareTo(7));
}
output
-1
1
0

Question 6 — Solution

dart
void main() {
  var words = ['Dart', 'flutter', 'Code'];
  words.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
  print(words);
}
output
[Code, Dart, flutter]

Question 7 — Solution

dart
void main() {
  var animals = ['elephant', 'cat', 'horse'];
  animals.sort((a, b) => a.length.compareTo(b.length));
  print(animals);
}
output
[cat, horse, elephant]

Question 8 — Solution

dart
void main() {
  final prices = [300, 100, 200];
  var sorted = List.of(prices);
  sorted.sort();
  print(sorted);
  print(prices);
}
output
[100, 200, 300]
[300, 100, 200]

Question 9 — Solution

dart
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);
}
output
[92, 81, 75]

A shorter way to take the first few elements of a list comes in Lecture 046.

Question 10 — Solution

dart
void main() {
  var names = ['Hina', 'ali', 'Sara', 'zayan'];
  names.sort((a, b) => b.toLowerCase().compareTo(a.toLowerCase()));
  print(names);
  print('Last alphabetically: ${names.first}');
}
output
[zayan, Sara, Hina, ali]
Last alphabetically: zayan

Sorted Z to A, the name that comes last in the alphabet is at the front, so it is first.


Quick Revision

  1. Does sort() create a new list or change the existing one?
  2. Why does var s = list.sort(); fail?
  3. What do negative, zero and positive results from compareTo mean?
  4. How do you turn an ascending comparator into a descending one?
  5. Why does 'Zayan' come before 'ali' with plain sort()?
  6. How do you keep the original order while getting a sorted version?
  7. Why does print(list.reversed) show round brackets?
  8. What does shuffle() do, and what does it return?

Key Takeaways

  • sort() orders a list in place, smallest first, and returns void.
  • 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 — use List.of(a) or a.toList() before sorting.
  • reversed is an Iterable that 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.


Video lecture

Subscribe
Placeholder video — the real recording isn't linked yet.