Menu
CoddyTech

Membership

Part of the Fundamentals section of Coddy's GDScript journey. Lesson 75 of 92.

The in operator checks whether a value is an element of an array. It returns true or false; not in returns the opposite:

var pets := ["cat", "dog"]
print("cat" in pets)
print("fox" not in pets)
print("fox" in pets)
true
true
false

Arrays also have methods for searching:

  • has(value) returns true if the value is in the array, like in
  • find(value) returns the index of the first matching element, or -1 if there is none
  • count(value) returns how many elements are equal to the value
var drops := ["coin", "gem", "coin"]
print(drops.has("gem"))
print(drops.find("coin"))
print(drops.find("key"))
print(drops.count("coin"))
true
0
-1
2

On strings, in looks for text inside the string: "ell" in "hello" is true.

challenge icon

Challenge

Easy

The program reads two lines of values separated by commas into the arrays first and second (already written).

Print a new array with every element of first that is not in second, in the order of first. Keep duplicates. For the inputs 1,2,3,4,5 and 2,4,6, the output is:

["1", "3", "5"]

Try it yourself

extends Node

func _ready():
	var first := OS.read_string_from_stdin().split(",")
	var second := OS.read_string_from_stdin().split(",")
	# Write your code below
quiz iconTest yourself

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

All lessons in Fundamentals

Practice on your own: Online GDScript compiler