Part I — Foundations · Chapter 5 · Lesson 2 of 5 · 10 min read
Lesson 2: Indexing, Slicing, Mutation, Copying, and Equality
Lesson level: Foundation
Purpose: Access and update collection data safely while reasoning about boundaries, shared references, copies, and value comparison.
Learning objectives
By the end of this lesson, you should be able to:
- read list and string elements by index;
- select subsequences with slices;
- access map values by string key;
- validate indices and keys before access;
- distinguish rebinding from collection mutation;
- explain aliasing between bindings;
- create deliberate shallow copies;
- reason about nested-copy limitations; and
- compare scalar and collection values appropriately.
1. Indexing selects one element
Lists, strings, and other indexed values use zero-based positions. The first element is at index 0, the second at index 1, and the last valid nonnegative index is one less than the collection length.
let priorities = ["low", "medium", "high"] print(priorities[0]) print(priorities[2])
The outputs are low and high. An index identifies a position, not an item count.
2. String indexing
A string can be indexed to select a character position:
let code = "PEA" print(code[0]) print(code[2])
The selected results are P and A. Treat indexing as reading a position; string construction and transformation should use clear string operations rather than assuming arbitrary in-place character mutation.
3. Valid index boundaries
For a collection of length n, valid nonnegative indices run from 0 through n - 1. Accessing an invalid index produces an error.
let values = [10, 20, 30] let index = 2 if index >= 0 and index < 3 { print(values[index]) }
In reusable code, derive bounds from the collection through supported operations rather than duplicating a literal length that can drift.
4. Map key access
Maps are accessed by string key rather than numeric position:
let case = {"id": "CASE-1042", "impact": 6} print(case["id"])
A key describes field meaning. Key spelling and case are part of the contract.
5. Check key presence first
Do not access an untrusted map key before confirming its presence through supported map operations. A missing key differs from a present key whose value is null.
Validation order is: confirm the map shape, confirm the required key, read the value, check nullability, then validate the value's category and domain constraints.
6. Slicing selects a subsequence
A slice selects a range from an indexed value. The start is included and the stop is excluded, matching the range boundary model used in loops.
let values = [10, 20, 30, 40, 50] let middle = values[1:4]
The result contains 20, 30, and 40. The stop index 4 marks the first element not included.
7. Slice boundaries
Reason about a slice with three questions:
- What is the first included index?
- What is the first excluded index?
- How many elements should the result contain?
For values[1:4], the included indices are 1, 2, and 3, producing three elements.
8. String slices
Slicing a string selects a substring:
let identifier = "CASE-1042" let prefix = identifier[0:4]
The result is CASE. Use slices when positions are defined by the contract; otherwise prefer named parsing or string operations that reveal intent.
9. Empty slices
A valid slice can produce an empty result when its selected interval contains no elements. This differs from an invalid single-element index, which cannot return an element.
Test empty collections, equal start and stop positions, beginning boundaries, ending boundaries, and the full selected range.
10. Slices and copies
A slice produces a separate outer collection value rather than an alias to the original list container. Mutating the outer slice should not change the original list structure. However, nested mutable values can still be shared, so the copy is shallow unless the contract states otherwise.
11. Mutation changes an existing collection
Mutation changes part of a list or map while the binding continues to refer to the same collection value.
let scores = [8, 9, 10] scores[1] = 12 let case = {"status": "new"} case["status"] = "assigned"
The list's second element changes, and the map's status field changes.
12. Rebinding versus mutation
Rebinding assigns a different value to a name. Mutation updates the collection already referenced by that name.
let values = [1, 2, 3] values[0] = 9 values = [4, 5, 6]
The first update mutates the original list. The second rebinds values to another list.
13. const protects the binding
A const declaration prevents rebinding. When the bound value is mutable, const does not automatically imply a deeply immutable object. Keep the distinction explicit and avoid mutating collections that readers reasonably expect to remain fixed.
For policy data, prefer functions that return new collections when mutation would obscure ownership or create shared-state risk.
14. Validate writable targets
Before assigning through an index or key, confirm that the target supports mutation and that the position or key operation is valid. An arbitrary calculated expression is not a writable location.
Keep mutation local, purposeful, and close to its validation. Document which function owns the collection and which callers may retain references to it.
15. Mutation and invariants
Every update should preserve collection invariants. Examples include:
- all scores remain within an approved range;
- every inventory item retains required keys;
- quantities remain nonnegative;
- parallel lists remain aligned; and
- a decision map keeps compatible priority and response fields.
Validate the proposed value before writing it, then verify any relationship that spans several fields.
16. Assignment can create aliases
When one binding receives an existing list or map, both names may refer to the same mutable collection.
let original = [1, 2, 3] let alias = original alias[0] = 9
If the bindings share the same list, reading original[0] now returns 9. The assignment copied the reference, not an independent outer collection.
17. Why aliasing matters
Aliasing makes an update visible through every reference to the same collection. This can be intentional, but hidden aliases make local-looking changes affect distant code.
Before mutating a collection, ask who else can reference it. Establish ownership rules: mutate only owned collections, or return a new value when callers may share the original.
18. Shallow copies
A shallow copy creates a new outer list or map while reusing nested values. A full list slice is one way to produce a separate outer list where supported:
let original = [1, 2, 3] let copied = original[0:3] copied[0] = 9
The outer list structure is separate, so the original first element remains 1.
19. Nested aliasing after a shallow copy
Consider a list of maps:
let original = [{"quantity": 2}, {"quantity": 5}] let copied = original[0:2] copied[0]["quantity"] = 9
The outer lists are separate, but the nested first map may still be shared. A shallow copy does not recursively duplicate nested collections.
20. Deliberate deep copying
When nested independence is required, construct new nested lists and maps deliberately or use a documented library operation that guarantees the needed copy depth. State whether an interface returns shared data, a shallow copy, or a fully independent portable structure.
Deep copying every value automatically can be expensive and may hide an unclear ownership design. Copy only to satisfy a defined contract.
21. Copy-before-update pattern
- Validate the source structure.
- Create a new outer collection.
- Copy or rebuild each nested value at the required depth.
- Apply validated changes to the new structure.
- Verify invariants.
- Return the new structure and leave the source unchanged.
This pattern is useful when a function should behave like a transformation rather than an in-place editor.
22. Scalar equality
The equality operators compare values. Strings compare text exactly, booleans compare their true or false value, null equals null, and numbers compare numerically under the language's value rules.
print("gold" == "gold") print(true != false) print(null == null)
Do not confuse equality with assignment. Equality produces a boolean; assignment changes a target.
23. Collection equality
Lists and maps compare by their contained values rather than merely by whether two bindings refer to the same container. List order matters. Maps must have corresponding keys and equal values.
Nested collections compare recursively. A small difference deep inside a structure makes the whole comparison unequal.
24. Equality versus aliasing
Two collections can be equal without being the same shared collection, and two aliases can refer to the same collection. Equality alone does not reveal whether later mutation will be shared.
Test independence by applying a controlled mutation to a copy in a dedicated test and confirming whether the source changes. Do not use destructive probes in production logic.
25. Floating-point comparison
Exact equality may be unsuitable for values produced by floating-point arithmetic. Use an explicit tolerance:
let difference = calculated - expected if difference < 0 { difference = -difference } let close_enough = difference <= tolerance
The tolerance belongs in the domain contract. Do not choose it merely to make a failing test pass.
26. Equality and domain equivalence
Value equality and business equivalence are not always identical. Case-normalized labels, reordered records, or rounded measurements may be equivalent only after an explicit normalization policy.
Keep normalization separate and visible. Compare canonical values after validation rather than silently converting unrelated inputs during equality checks.
27. Common mistakes
- Using one-based indexing. Index 1 selects the second element.
- Using the collection length as a valid index. The final valid index is length minus one.
- Forgetting the exclusive slice stop. The stop position is not included.
- Accessing a missing key before validation. The failure occurs before a useful invalid result can be returned.
- Confusing rebinding with mutation. They affect references differently.
- Assuming const means deep immutability. The binding and the collection's contents are separate concerns.
- Assuming assignment copies a collection. It may create an alias.
- Assuming a shallow copy duplicates nested values. Nested collections may remain shared.
- Using exact equality for derived floats. Apply a justified tolerance.
- Assuming equality proves independence. Equal collections may still be different or shared objects.
Guided practice
- Identify the valid indices for a five-item list.
- Predict the result of slicing indices 1 through 4 with an exclusive stop.
- Explain why an empty slice differs from an invalid index.
- Write a safe map-access sequence for a nullable field.
- Distinguish list mutation from rebinding the list variable.
- Predict how a mutation through an alias affects the original.
- Create an independent outer-list copy with a full slice.
- Explain why nested maps may remain shared after a shallow copy.
- Compare two equal lists created separately, then explain why equality does not prove aliasing.
- Write a tolerance comparison for a derived floating-point result.
Hands-on lab: Build a safe inventory updater
Scenario. An inventory is represented as a list of string-keyed item maps. Build functions that read, update, copy, and compare the inventory without accidental shared mutation.
Item contract
- sku — nonempty string;
- name — nonempty string;
- quantity — nonnegative integer;
- unit_price — nonnegative number; and
- active — boolean.
Requirements
- Create at least four item maps inside one inventory list.
- Read the first and last items safely.
- Create a middle inventory slice and verify its expected length.
- Implement a validated quantity update by index.
- Implement a validated field update by key.
- Demonstrate aliasing with a temporary controlled example.
- Create a separate outer copy and show that outer-list mutation does not change the source.
- Demonstrate nested sharing after a shallow copy.
- Build a transformation that returns independently rebuilt item maps.
- Compare source, shallow copy, and rebuilt copy before and after updates.
- Verify nonnegative quantity and complete-item invariants.
- Keep calculation and update functions free of printing.
Test cases
- first, middle, and last valid indices;
- negative and too-large indices;
- empty inventory;
- existing and missing keys;
- valid, zero, and negative quantities;
- equal but independently built inventories;
- shared nested mutation after shallow copying; and
- floating-point comparison using a documented tolerance.
Deliverable. Submit the source, ownership notes, alias diagram, test matrix, before-and-after states, equality results, and invariant evidence.
Review questions
- Why does zero-based indexing make the last valid index length minus one?
- How does a slice's stop boundary behave?
- Why can an empty slice be valid while an invalid index fails?
- How does map key access differ from list indexing?
- What validation should precede an untrusted map read?
- How does mutation differ from rebinding?
- What does const protect when it refers to a collection?
- How can assignment create aliases?
- What does a shallow copy duplicate?
- Why may nested collections remain shared?
- How does collection equality differ from shared identity?
- When should floating-point values be compared with a tolerance?
Applied challenge: Non-destructive order revision
Build a function that receives a portable order map containing a list of line-item maps and returns a revised order without mutating the source. It must validate the target item index, rebuild the required nested structures, update quantity, and recalculate summary fields.
Prove that the source and revised order are equal before the change except for intentionally updated fields, and prove that later nested mutation of the revised order does not alter the source. Include invalid-index, missing-key, null-field, negative-quantity, empty-order, and floating-point tolerance tests.
Success criteria
- All indices and keys are validated before access.
- Slice boundaries are explicit and tested.
- Mutation ownership is documented.
- The revised order has independently rebuilt nested values.
- The source remains unchanged.
- Equality tests cover both expected matches and expected differences.
- Floating-point comparisons use a documented tolerance.
- All order invariants remain true.
Lesson summary
Indexing reads one position, while slicing selects a subsequence with an exclusive stop boundary. Collection updates require valid writable targets and preserved invariants. Rebinding changes which value a name references; mutation changes an existing collection. Assignment can create aliases, shallow copies separate only the outer collection, and nested values may remain shared. Equality compares values but does not prove reference independence, while derived floating-point values often require tolerance-based comparison.
Next lesson: Traversal, Transformation, Filtering, and Aggregation
Lesson status: Approved.