Adding and Removing
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 33 of 78.
To add a member, assign true to its key. Adding a member that is already in the set changes nothing, so when you need to know whether it was new, check with has() first:
var inventory := {"rope": true}
if inventory.has("torch"):
print("Already have torch")
else:
inventory["torch"] = true
print("Added torch")To remove a member, call erase(). It returns true when the member was removed and false when it was not in the set. A missing member is never an error:
print(inventory.erase("rope")) # true
print(inventory.erase("map")) # false
print(inventory) # { "torch": true }Because erase() returns a boolean, you can use it directly as a condition: if inventory.erase("map"): runs its block only when "map" was a member.
clear() removes every member, size() counts them and is_empty() is true for a set with no members.
Challenge
EasyThe program reads commands, one per line, until the line done. Each command is add ITEM or remove ITEM. The starter code already splits each command into action and item.
- For
add: if the item is new, add it to the setinventoryand printAdded ITEM. Otherwise printAlready have ITEM. - For
remove: if the item is in the set, remove it and printRemoved ITEM. Otherwise printNo ITEM to remove.
After done, print Inventory: followed by the members joined with , , or Inventory: empty when the set is empty. For the input:
add torch
add rope
add torch
remove map
remove rope
donethe output is:
Added torch
Added rope
Already have torch
No map to remove
Removed rope
Inventory: torchTry it yourself
extends Node
func _ready():
var inventory := {}
while true:
var command := OS.read_string_from_stdin()
if command == "done":
break
var parts := command.split(" ")
var action := parts[0]
var item := parts[1]
# Add or remove the item
# Print the inventory
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler