Menu
CoddyTech

Iterating With Indexes

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

A loop over the elements gives you each value, but not its position. When you need the index too, loop over the indexes with range() and read each element with square brackets:

var fruits := ["apple", "banana", "orange"]
for i in range(fruits.size()):
	print("Index %d: %s" % [i, fruits[i]])
Index 0: apple
Index 1: banana
Index 2: orange

range(fruits.size()) gives 0, 1 and 2: exactly the indexes of the array. On each pass, i is the index and fruits[i] the element.

The index is also what lets you change the array inside a loop. Assigning to the loop variable of for price in prices: changes only that variable, while assigning to prices[i] changes the array:

var prices := [2, 5]
for i in range(prices.size()):
	prices[i] *= 2
print(prices)
[4, 10]
challenge icon

Challenge

Easy

The program reads a line of whole numbers separated by commas into the array numbers (already written).

Print an array with the indexes of the numbers that are below 50 or divisible by 5. For the input 80,4,99,36,34:

  • 80 (index 0) is divisible by 5: included
  • 4 (index 1) is below 50: included
  • 99 (index 2): not included
  • 36 (index 3) and 34 (index 4) are below 50: included

The output is:

[0, 1, 3, 4]

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))
	# 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