Menu
CoddyTech

Sequence Operators

Part of the Fundamentals section of Coddy's GDScript journey. Lesson 74 of 92.

The + operator joins two arrays into a new array, the elements of the first followed by those of the second:

var team_a := [1, 2, 3]
var team_b := [4, 5, 6]
var everyone := team_a + team_b
print(everyone)
[1, 2, 3, 4, 5, 6]

The two original arrays do not change. To add the elements of an array to an existing one, use +=:

var loot := ["coin"]
loot += ["gem", "key"]
print(loot)
["coin", "gem", "key"]

+ joins strings the same way: "Good" + " " + "Morning" is "Good Morning".

== compares two arrays element by element, in order. [1, 2] == [1, 2] is true, and [1, 2] == [2, 1] is false.

GDScript has no repetition operator: [1, 2] * 3 and "#" * 3 are errors. Repeat an array with += in a loop, and a string with the repeat() method:

var pattern := []
for i in range(3):
	pattern += [1, 2]
print(pattern)
print("*".repeat(5))
[1, 2, 1, 2, 1, 2]
*****
challenge icon

Challenge

Easy

The program reads a line of whole numbers separated by commas into numbers, and a second line into repeats (already written).

  1. Join numbers with itself using +
  2. Build pattern: that doubled array, repeats times in a row
  3. Print pattern

For the inputs 1,2,3 and 2, the output is:

[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]

Try it yourself

extends Node

func _ready():
	var parts := OS.read_string_from_stdin().split(",")
	var numbers: Array[int] = []
	for part in parts:
		numbers.append(int(part))
	var repeats := int(OS.read_string_from_stdin())
	# Write your code below
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