Modifying Arrays
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 64 of 92.
You can change an element of an array by assigning a new value to its index:
var fruits := ["apple", "banana", "cherry"]
fruits[1] = "orange"
print(fruits)["apple", "orange", "cherry"]The element at index 1, "banana", is replaced by "orange". The other elements and the size stay the same.
Negative indexes work here too. fruits[-1] = "kiwi" replaces the last element.
Assignment only replaces elements that exist. In the 3-element array above, fruits[3] = "kiwi" is an error: index 3 does not exist, and assigning to it does not add an element.
Challenge
EasyThe array team holds four player names. The program reads two lines from the input:
index: the position of the player to replace (it can be negative, counting from the end)new_player: the new name
Replace the name at index with new_player. The print(team) line is already written. For the inputs 1 and Zoe, the output is:
["Ana", "Zoe", "Cleo", "Dev"]Try it yourself
extends Node
func _ready():
var team := ["Ana", "Ben", "Cleo", "Dev"]
var index := int(OS.read_string_from_stdin())
var new_player := OS.read_string_from_stdin()
# Replace the player at index with new_player
print(team)
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