Menu
Coddy logo textTech

What is a Set?

Part of the Logic & Flow section of Coddy's Dart journey — lesson 17 of 65.

A Set is a collection data structure that stores unique elements in no particular order. Unlike a List, which can contain duplicate values and maintains the order of elements, a Set automatically ensures that each element appears only once.

The key difference between a List and a Set is how they handle duplicates. When you try to add an element that already exists in a Set, it simply ignores the duplicate and keeps only one copy of that element.

// List allows duplicates
List<String> fruits = ['apple', 'banana', 'apple', 'orange'];
print(fruits);  // ['apple', 'banana', 'apple', 'orange']

// Set automatically removes duplicates
Set<String> uniqueFruits = {'apple', 'banana', 'apple', 'orange'};
print(uniqueFruits);  // {'apple', 'banana', 'orange'}

This automatic duplicate removal makes Set particularly useful when you need to ensure uniqueness in your data, such as storing user IDs, email addresses, or any collection where each item should appear only once.

Cheat sheet

A Set is a collection that stores unique elements in no particular order, automatically removing duplicates:

// List allows duplicates
List<String> fruits = ['apple', 'banana', 'apple', 'orange'];
print(fruits);  // ['apple', 'banana', 'apple', 'orange']

// Set automatically removes duplicates
Set<String> uniqueFruits = {'apple', 'banana', 'apple', 'orange'};
print(uniqueFruits);  // {'apple', 'banana', 'orange'}

Use Set when you need to ensure uniqueness in your data, such as storing user IDs or email addresses.

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow