List comprehension

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

Is there a way to implement list comprehensions to GDScript? Like in this code in Python

[n for n in range(5)]

what’s the GDScript equivalent to this?

:bust_in_silhouette: Reply From: kidscancode

GDScript is not Python, and does not have comprehensions.

:bust_in_silhouette: Reply From: magicalogic

You could write your own scripts that do that. Actually I’ll try that and hopefully share it in github.

Scripts can’t extend GDScript syntax, so you’d have to provide this with a method and string… and it would be quite inefficient.

Godot 4.0 will have first-class functions, lambdas, and map/filter/reduce functions in the Array class.

Calinou | 2021-05-07 14:39

:bust_in_silhouette: Reply From: dmphysics37

I’d noticed something nifty playing around with gdscript.

var xxx = Array(PoolIntArray(range(3)))

The above is equal to python 3’s:

xxx = list(range(3))

Or

xxx = [n for n in range(3)]

Hope it helps

:bust_in_silhouette: Reply From: edupo

You can use a for loop and an empty array:

var my_range = []
for n in range(5):
    var o = n  # Do something interesting with n here.
    my_range.append(o)
:bust_in_silhouette: Reply From: SodaRamune

This is kind of a silly, over-complicated way of doing it, but it works:

var doubled_array = (func(amt=5, a=[]): for n in range(amt): a.append(n * 2); if n + 1 == amt: return a).call()

The Python equivalent would be:

doubled_list = [n * 2 for n in range(5)]

At that point, you’re better off just making a regular for loop with a previously initialized empty array like edupo suggested.

:bust_in_silhouette: Reply From: Alkhemi

Since Godot 4, You can use map for this

var doubled = range(5).map(func(n): return n * 2)

python equivalent:

doubled = [n * 2 for n in range(5)]
1 Like