For Beginners

Lesson 15/23

Replacing and Adding Elements to a List

Elements in a list are not there forever. You can replace them — just some or all — anytime using indices. Run this script:

♥list = Adam❚Eva❚John❚Mary
♥list⟦1⟧ = Peter
dialog ♥list

The list has changed: now Peter is the first element, not Adam. It's because in the second line you told the robot to replace the first element of the ♥list with Peter. Experiment with replacing other elements of the ♥list.

You can also add an element to existing list:

♥list = Adam❚Eva❚John❚Mary
dialog ♥list⟦count⟧
♥list⟦⟧ = Jack
dialog ♥list
dialog ♥list⟦count⟧

When you run this script, the first dialog box will display 4, as there are that many elements in the list declared in the first line. The next dialog will show expanded list with a new element at its end — Jack, and the last dialog will present you with a new element count, which now equals 5. The code responsible for the change is in the third line: the empty double brackets in ♥list⟦⟧ = Jack cause adding Jack to the list ♥list.

Lists can make some mess if their elements are of mixed types. The next lesson will explain that.