Lists: Adding and removing
● Beginner3 min
push adds an item to the end and pop takes the last one off; + joins two lists; filter keeps only the items you want.
fn main() {
let cart = ["pen", "book"]
cart.push("bag")
print(cart)
cart = cart.filter(item => item != "book")
print(cart)
print(cart.len())
}The program ran and printed:
kavach run add-remove.kav
["pen", "book", "bag"]["pen", "bag"]2
filter makes a new list of the items its test is true for. Assigning it back to cart removes the rest.
Two lists together
fn main() {
const evens = [2, 4]
const all = evens + [6, 8]
print(all)
print(evens)
let log = ["start"]
log += ["step 1", "step 2"]
print(log)
}The program ran and printed:
kavach run plus.kav
[2, 4, 6, 8][2, 4]["start", "step 1", "step 2"]
evens + [6, 8]is a new list: the items of the first, then those of the second. Neither changes.log += ["step 1", "step 2"]adds the items to the end oflog, so likepushit needs alet. When nothing else holds the list, it grows in place, without copying what it holds.- Both lists hold the same type.
Taking the last item
pop() takes the last item out and gives it, or none for an empty list. It changes the list, so it needs a let too:
fn main() {
let stack = [1, 2, 3]
const top = stack.pop() ?? 0
print(top)
print(stack)
let empty: [Int] = []
print(empty.pop())
}The program ran and printed:
kavach run pop.kav
3[1, 2]none