Lists
Lists in Acton are ordered mutable sequences, similar to a to-do list where items have a specific order. Lists can only contain values of one type at a time due to Acton's static type system.
Think of a list like a row of boxes, where each box can hold one item. All boxes must hold the same type of thing - you can't mix apples and hammers!
Creating Lists
Create a list with initial values |
|
Create an empty list - type will be inferred when you add the first item |
|
Lists in Acton are implemented as dynamic arrays with amortized O(1) append operations. The underlying storage grows geometrically to maintain performance characteristics.
Basic Operations
Create a list and add items |
|
Access items by index (counting starts at 0) |
|
Print the entire list - must convert to string first |
|
Get a slice of the list |
|
Common mistake: Remember that indexing starts at 0, not 1! So the first item is at position 0, the second at position 1, and so on.
Slicing: The slice l[start:stop]
includes the item at start
but excludes the item at stop
. This is the same behavior as Python.
Modifying Lists
Add items to the end - O(1) amortized time |
|
Insert at a specific position - O(n) time complexity |
|
Remove and return an item |
|
Extend a list with another list |
|
List Utilities
Sort a list (returns a new list) |
|
Reverse a list in-place |
|
Copy a list - creates a shallow copy |
|
Clear all items from a list |
|
Performance characteristics:
append()
- O(1) amortized (may occasionally resize)insert()
- O(n) as elements need to be shiftedpop()
- O(1) for last element, O(n) for arbitrary indexextend()
- O(k) where k is the length of the added listreverse()
- O(n) in-place operationcopy()
- O(n) creates new list
List Comprehensions
List comprehensions provide a concise way to create lists based on existing sequences or ranges. They're like a recipe for making a new list from an existing one!
List comprehensions might look complex at first, but they follow a simple pattern:
[expression for item in sequence]
- "give me expression for each item in sequence"
Create a list of squares (multiply each number by itself) |
|
Filter with a condition |
|
Multiple iterators (cartesian product) |
|
Advanced Comprehensions
Nested list comprehension |
|
Transform existing list |
|
Filter and transform |
|
Performance tip: When using multiple iterators with filtering, place filters as early as possible:
# Good - filters early, reduces iterations
result = [x + y for x in big_list if condition(x) for y in small_list]
# Bad - filters late, wastes computation
result = [x + y for x in big_list for y in small_list if condition(x)]
Type Safety
All items in a list must be of the same type. Mixing types like ["foo", 1]
will result in a compiler error.
Valid: homogeneous list |
|
Invalid: mixed types |
|