Array Slicing
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 73 of 92.
The slice() method returns a new array with part of the elements. slice(begin, end) takes the elements from index begin up to, but not including, index end:
var numbers := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers.slice(2, 6))[2, 3, 4, 5]Without end, the slice goes to the end of the array:
print(numbers.slice(5))[5, 6, 7, 8, 9]Negative indexes count from the end. slice(-3) takes the last three elements, and slice(0, -2) everything except the last two:
print(numbers.slice(-3))
print(numbers.slice(0, -2))[7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7]A third argument, the step, takes every n-th element. slice(1, 8, 2) takes indexes 1, 3, 5 and 7:
print(numbers.slice(1, 8, 2))[1, 3, 5, 7]slice() does not change the original array: numbers still holds all ten elements.
Challenge
EasyThe program reads a line of items separated by commas into the array items (already written). Print the middle part of the array with slice():
- If the number of items is odd, print the middle item and one item on each side (3 items; with a single item, print that item)
- If it is even, print the two middle items
For apple,banana,orange,grape the output is ["banana", "orange"], and for a,b,c,d,e it is ["b", "c", "d"].
Try it yourself
extends Node
func _ready():
var items := OS.read_string_from_stdin().split(",")
# Print the middle items
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