6. Collections
Lists
Ordered sequences of any values.
let nums = [10, 20, 30];
print(nums[0]); // 10 (indexing, 0-based)
print(nums[-1]); // 30 (negative counts from the end)
nums[1] = 99; // assign by index
print(len(nums)); // 3
nums.push(40); // add to the end
print(nums); // [10, 99, 30, 40]
let last = nums.pop(); // remove & return the last
print(last); // 40
Iterating
let total = 0;
for n in [1, 2, 3, 4] {
total = total + n;
}
print("sum:", total); // 10
print("built-in sum:", sum([1,2,3,4])); // 10
print(min([5,2,8]), max([5,2,8])); // 2 8
print(sorted([3,1,2])); // [1, 2, 3]
Dictionaries (maps)
Key → value pairs. Keys are strings.
let person = { "name": "Ember", "age": 20 };
print(person["name"]); // Ember
person["age"] = 21; // update
person["city"] = "Istanbul"; // add
print(person.keys()); // [name, age, city]
print(person.values());
print(person.has("age")); // true
print("name" in person); // true
print(len(person)); // 3
Iterating a dict (keys)
let scores = { "math": 90, "science": 85 };
for subject in scores {
print(subject, "->", scores[subject]);
}
Nesting
Lists and dicts can hold anything, including each other:
let users = [
{ "name": "A", "age": 30 },
{ "name": "B", "age": 25 }
];
for u in users {
print(u["name"], u["age"]);
}
print(users[0]["name"]); // A
Kitteniverse Studios