Menu
CoddyTech

What is a Set?

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 31 of 78.

A set is a collection of unique values: each value is in it once or not at all. The question you ask a set is "is this value a member?". The badges a player has earned, the levels already visited and the usernames already taken are sets.

An array keeps every copy you add:

var pickups := ["sword", "shield", "sword"]
print(pickups.size()) # 3

GDScript has no Set type. Instead, you use a dictionary: its keys are unique, so the keys are the members of the set. The values are not used, and by convention every value is true:

var items := {"sword": true, "shield": true}
items["sword"] = true # already a member: nothing changes
print(items.size()) # 2
print(items.keys()) # ["sword", "shield"]

keys() returns the members as an array, in the order they were first added. An empty set is an empty dictionary, {}.

A set literal lists each member once. Writing the same key twice inside {} is an error that stops the program before it runs.

To make the set's type explicit, use a typed dictionary: var badges: Dictionary[String, bool] = {}

challenge icon

Challenge

Easy

A player played four matches and earned one badge in each. Some badges repeat. The program reads four lines of input, one badge name per line.

Add each badge to the set badges, then print the number of different badges and the members of the set as an array. For the badges Sniper, Medic, Sniper and Builder, the output is:

Unique badges: 3
["Sniper", "Medic", "Builder"]

Try it yourself

extends Node

func _ready():
	var badges := {}
	for i in range(4):
		var badge := OS.read_string_from_stdin()
		# Add the badge to the set
		pass

	# Print the number of badges and the badges
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