Menu
CoddyTech

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 end
  • insert(index, value) puts a value at an index and moves the following elements one place right
  • pop_back() removes the last element and returns it
  • remove_at(index) removes the element at an index
  • erase(value) removes the first element equal to a value; if there is none, nothing happens
  • clear() 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 icon

Challenge

Easy

The program reads two items from the input: new_item and used_item. Change inventory in this order:

  1. Add new_item to the end
  2. Remove used_item by its value (if it is not in the array, nothing changes)
  3. Insert "map" at the start, index 0

The two print() lines are already written. For the inputs bow and shield, the output is:

["map", "sword", "potion", "bow"]
4

Try 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())
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