Simple way to get the first n integers from array?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By miss_bisque

I have the following code that generates a random number, stores it in the list, and then removes that number so there are no repeats

var list = range(0,10)
var sample =[]

func _ready():
	randomize()
	for i in range(4):
		var x = randi()%list.size()
		sample.append(list[x])
		list.remove(x)

sample is now a list of 4 integers [X X X X]. I’d like to be able to get the first 3 integers from the list and index into them later, and use the last number for something else. In python, I could do something like sample[0:3] but I’m now learning its much harder to do something like this in godot.

Any good workarounds?

:bust_in_silhouette: Reply From: jgodfrey

Maybe you want the Array.slice() method? Here’s an example:

func _ready():
	var a = [0, 1, 2, 3]
	var b = a.slice(0, 2)
	print(a)
	print(b)

Output:

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

Details in the docs:

:bust_in_silhouette: Reply From: Wakatta

Hmm its funny i thought sample[0:3] applied :frowning:

var nth = sample.slice(0, 2)