Menu
CoddyTech

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 icon

Challenge

Easy

The 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 set inventory and print Added ITEM. Otherwise print Already have ITEM.
  • For remove: if the item is in the set, remove it and print Removed ITEM. Otherwise print No 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
done

the output is:

Added torch
Added rope
Already have torch
No map to remove
Removed rope
Inventory: torch

Try 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
quiz iconTest yourself

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

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler