CodeBlanks Logo Icon CodeBlanks

Set operations

Learn Set management with add, contains and remove.

Set operations

You add to a Set with add, remove with remove, and ask membership with contains. For example fruits.add('cherry'); places a new value in the Set.

contains returns a boolean: fruits.contains('apple') gives true when 'apple' is in the Set. remove drops the item; if it is not there, it does nothing silently.

The length property tells you how many items the Set holds; isEmpty and isNotEmpty are handy for quick checks. A Set offers no indexed access; reach for a List when order matters.

contains and remove

contains asks whether a value lives in the Set. For example fruits.contains('banana') returns false when 'banana' is absent. This is much faster than a list's indexOf.

remove throws the given value out of the Set. fruits.remove('apple') deletes 'apple'; if it is missing, no error is raised. The return value is a boolean: true if removed, false otherwise.

Together these three methods keep a Set alive: add to place, contains to check, remove to clean.

Practice Three friends list

Create a Set<String>. Use add to insert three friend names, then use contains to print whether the name 'Ayşe' is in the Set.

Starter code

main.dart
void main() {
  var friends = <String>{};
  // add three names

  // contains check for 'Ayşe' prints false
}

Sample solution

main.dart
void main() {
  var friends = <String>{};
  friends.add('Mert');
  friends.add('Deniz');
  friends.add('Cem');
  print(friends.contains('Ayşe'));
}

Expected output

false

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 The add call

Question
void main() {
  var fruits = <String>{'apple'};
  fruits.____('pear');
  print(fruits);
}
Answer
void main() {
  var fruits = <String>{'apple'};
  fruits.add('pear');
  print(fruits);
}

Explanation: add appends a single element.

2 What does contains return?

main.dart
var fruits = <String>{'apple'};
print(fruits.contains('banana'));
  • void
  • String
  • bool (true/false) Correct answer
  • int

Explanation: bool. contains answers the membership question with true or false.

3 Match the operations

Term Meaning
add Inserts an element
contains Tests membership
remove Drops an element
length Element count

All lessons in Beginner