Array Methods
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 65 of 92.
Arrays have methods that add and remove elements. You call a method with a dot after the array: party.append("mage").
append(value)adds one element to the endinsert(index, value)puts a value at an index and moves the following elements one place rightpop_back()removes the last element and returns itremove_at(index)removes the element at an indexerase(value)removes the first element equal to a value; if there is none, nothing happensclear()removes every element
var party := ["knight", "archer"]
party.append("mage")
party.insert(0, "healer")
print(party)["healer", "knight", "archer", "mage"]var last = party.pop_back()
print(last)
party.remove_at(1)
party.erase("archer")
print(party)mage
["healer"]append() always adds one element. Appending an array puts the whole array inside as a single element. To add each element of another array, use append_array():
var a := [1, 2]
a.append([3, 4])
print(a)
var b := [1, 2]
b.append_array([3, 4])
print(b)[1, 2, [3, 4]]
[1, 2, 3, 4]Challenge
EasyThe program reads two items from the input: new_item and used_item. Change inventory in this order:
- Add
new_itemto the end - Remove
used_itemby its value (if it is not in the array, nothing changes) - Insert
"map"at the start, index0
The two print() lines are already written. For the inputs bow and shield, the output is:
["map", "sword", "potion", "bow"]
4Try it yourself
extends Node
func _ready():
var inventory := ["sword", "shield", "potion"]
var new_item := OS.read_string_from_stdin()
var used_item := OS.read_string_from_stdin()
# 1. Add new_item to the end
# 2. Remove used_item
# 3. Insert "map" at the start
print(inventory)
print(inventory.size())
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler