Neon
← Back to VariablesNext: Containers →

Lists

Lists are ordered, indexable collections of objects (similar to arrays in other languages). They can hold any type of object, including other lists.

Creating Lists

# Empty list
empty_list = []

# List with elements
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, [2, 3]]

# List from a string (splits into characters)
chars = list("Neon")  # → ["N", "e", "o", "n"]

Accessing Elements

fruits = ["apple", "banana", "cherry"]
print(fruits[0])   # → "apple"
print(fruits[1])   # → "banana"

Modifying Lists

Operation Example Description
Append append(fruits, "orange") Adds "orange" to the end.
Insert insert(fruits, 1, "mango") Inserts "mango" at index 1.
Remove remove(fruits, 0) Removes element at index 0.
Length len(fruits) Returns the number of elements.
Reverse reverse(fruits) Reverses the list (returns a new list).
Sort sortAsc(fruits) Sorts in ascending order (modifies the list).
sortDesc(fruits) Sorts in descending order.
Index index(fruits, "banana") Returns the index of "banana" (or raises OutOfRange).
Count count(fruits, "apple") Counts occurrences of "apple".

List Operations

# Concatenation
list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2  # → [1, 2, 3, 4]

# Repetition
repeated = [1, 2] * 3  # → [1, 2, 1, 2, 1, 2]

# Membership check
"apple" in fruits  # → True
5 in numbers      # → False

List Comprehensions (Efficient List Building)

Neon provides listComp for efficient list construction.

Slow list construction:

squares = []
for (i, 0, 10) do
  if (i%2 == 0) then
    squares.append(i ** 2)
  end
end

Efficient version using listComp:

squares = listComp("i", 0, 10, 1, "i%2 == 0", "i ** 2")
# -> [0, 4, 16, 36, 64]

Deep Copying Lists

By default, copying a list shares references to its elements. Use copy() for a deep copy:

original = [[1, 2], [3, 4]]
shallow_copy = original  # Modifying shallow_copy affects original!
deep_copy = copy(original)  # Independent copy

← Back to VariablesNext: Containers →