Menu
CoddyTech

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 icon

Challenge

Easy

The array team holds four player names. The program reads two lines from the input:

  1. index: the position of the player to replace (it can be negative, counting from the end)
  2. 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)
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