Skip to content

Arrays ​

Instance methods on arrays. All methods support chaining.

Methods ​

MethodReturnsDescription
len()intElement count
push(val)Append element
pop()intRemove and return last
first()intFirst element
last()intLast element
min()intMinimum value
max()intMaximum value
sum()intSum of all elements
slice(start, end)arraySub-array
sort()arraySorted copy
reverse()arrayReversed copy
unique()arrayDeduplicated copy
concat(other)arrayConcatenate arrays
join(sep)stringJoin with separator
index_of(val)intFind element (-1 if missing)
remove(idx)Remove at index
insert(idx, val)Insert at index
map(fn)arrayTransform elements
filter(fn)arrayFilter elements
reduce(fn, init)intFold elements
each(fn)Call fn for each element
any(fn)intAny element matches (1/0)
every(fn)intAll elements match (1/0)
sort_by(cmp_fn)Sort with comparator

Indexing and Slicing ​

Index from the front with a[i], or from the back with a negative index - a[-1] is the last element:

wyn
a = [10, 20, 30, 40]
print(a[0].to_string())    // 10
print(a[-1].to_string())   // 40 - last
print(a[-2].to_string())   // 30 - second to last

Slice with a[i:j]. Either bound can be omitted:

wyn
a = [10, 20, 30, 40, 50]
head = a[:2]             // [10, 20]      - first two
tail = a[2:]             // [30, 40, 50]  - from index 2
mid  = a[1:4]            // [20, 30, 40]
copy = a[:]              // full copy

print(tail[-1].to_string())  // 50 - negative index works on slices too

Membership: in ​

Test whether an array contains a value with in / not in:

wyn
langs = ["python", "go", "rust"]
if "go" in langs { print("go supported") }
if "java" not in langs { print("no java") }

Method Chaining ​

wyn
// Chain any combination of array methods
result = [3, 1, 4, 1, 5, 9].sort().reverse()
print(result[0].to_string())  // 9

count = [5, 3, 1, 4, 2].filter(fn(x: int) -> bool { return x > 2 }).sort().len()
print(count.to_string())  // 3

words = "hello world foo".split(" ").sort().join(", ")
print(words)  // foo, hello, world

Functional ​

wyn
var doubled = nums.map(fn(x: int) -> int { return x * 2 })
var big = nums.filter(fn(x: int) -> bool { return x > 3 })
var total = nums.reduce(fn(acc: int, x: int) -> int { return acc + x }, 0)

Comprehensions ​

wyn
squares = [x * x for x in 0..10]
evens = [x for x in 0..20 if x % 2 == 0]

See Also ​

MIT License - v1.22.0