The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates. | Twitter

+2 votes

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?

in Engine by (42 points)

6 Answers

0 votes
Best answer

GDScript is not Python, and does not have comprehensions.

by (22,191 points)
selected by
0 votes

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

by (2,018 points)

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.

+2 votes

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


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

Hope it helps

by (18 points)
0 votes

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.
by (14 points)
0 votes

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.

by (14 points)
0 votes

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)]
by (20 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.