any and all
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 63 of 78.
any() and all() ask a yes-or-no question about a whole array. Both take a function that returns true or false for one element:
any()returnstrueif the function returnstruefor at least one element.all()returnstrueif the function returnstruefor every element.
var enemy_hp = [30, 0, 12]
print(enemy_hp.any(func(hp): return hp == 0))
print(enemy_hp.all(func(hp): return hp > 0))true
falseOne enemy has 0 HP, so any() is true, and that same enemy makes all() false.
Both stop as soon as the answer is known: any() at the first true, all() at the first false. They work with named functions too, like numbers.all(is_even).
On an empty array, any() returns false, because no element passes, and all() returns true, because no element fails.
Use them in a condition in place of a loop with a flag variable:
var inventory = ["sword", "key", "rope"]
if inventory.any(func(item): return item == "key"):
print("The door opens")Challenge
EasyThe program reads one line of scores separated by commas and stores them in the array numbers. This part is already written.
Print two lines:
Any perfect:followed bytrueif at least one score is100, otherwisefalseAll passed:followed bytrueif every score is50or more, otherwisefalse
Use any() for the first line and all() for the second. For the input 100,75,40, the output is:
Any perfect: true
All passed: falseTry it yourself
extends Node
func _ready():
var numbers := []
for part in OS.read_string_from_stdin().split(","):
numbers.append(int(part))
# Print the two lines with any() and all()
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 Student11Higher-Order Functions
The map MethodThe filter MethodThe reduce Methodany and allRecap - Email ValidatorRecap - Number Processor3Multi-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