Reference · Lists

range

signature
range(int, int=, int=) -> list

What it does

A list of ints. range(n) counts from 0 up to but not including n; range(a, b) counts from a up to but not including b; range(a, b, step) takes every stepth, down when step is negative. a..b is range(a, b) written as an operator. In a for that keeps no list, for i in range(a, b) counts without making one.

Examples

print(range(5))print(range(2, 5))print(range(-3, 1))print(0..3)for i in range(3) {    print("row", i)}print(range(0, 10, 3), range(10, 0, -3), range(5, 0, -1))
output
[0, 1, 2, 3, 4][2, 3, 4][-3, -2, -1, 0][0, 1, 2]row 0row 1row 2[0, 3, 6, 9] [10, 7, 4, 1] [5, 4, 3, 2, 1]

Edge cases

print(range(0), range(-2), range(5, 2), range(3, 3))print(range(1, 6), len(range(1, 6)))print(len(range(10000000)))print(range(5) | reverse, range(5) | map((i) => i * 2))print(range(0, 5, -1), range(3, 3, 2), range(0, 9, 4))let n = 0for i in range(0, 20000000) {    n += 1}print(n)
output
[] [] [] [][1, 2, 3, 4, 5] 510000000[4, 3, 2, 1, 0] [0, 2, 4, 6, 8][] [] [0, 4, 8]20000000

Errors

An argument that is not an int (a float, a string, nothing) is a runtime error, not an error value, and so is a range of more than ten million numbers.

this one fails
print(range(1.5))
output
line 1: `range` expects an int as argument 1, got float
this one fails
print(range(10000001))
output
line 1: range is too large
this one fails
print(range(0, 10, 0))
output
line 1: `range`: a step of 0 never gets anywhere

Chaining

range starts a pipeline: the numbers go on to a map, a filter or a sum. In a pipeline its own arguments are the ends.

print(range(1, 6) | map((x) => x * x) | sum)print(range(10) | filter((x) => x % 3 == 0))print(range(3) | map((i) => `item ${i + 1}`) | join(", "))
output
55[0, 3, 6, 9]item 1, item 2, item 3

See also

enumerate, map, take, vec.arange, vec.linspace

Thread
9Useful? Like it, or add to its thread below.

Thread 0 posts

On range(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo