Skip to content
Kavachकवच

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
add-remove.kav: Kavach code, then what running it prints

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"]
plus.kav: Kavach code, then what running it prints
  • 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 of log, so like push it needs a let. 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
pop.kav: Kavach code, then what running it prints