AP CSP Day 10: Side Effects And Mutation
Share
A side effect occurs when a procedure modifies a variable or data structure outside its own local scope, such as changing a global list or printing output. Mutation refers specifically to changing the contents of a list or other data structure in place. AP CSP exam questions testing side effects often show procedures that both return a value and modify an external list, requiring students to track both changes. Understanding the difference between a return value and a side effect is a frequently tested distinction.
📚 Study the Concept First (Optional) Click to expand ▼
Side Effects and List Mutation
What Is a Side Effect?
A side effect is any change a procedure makes beyond returning a value. Printing output, modifying a global variable, or changing a list passed to the procedure are all side effects.
Mutation vs. Return
A procedure can return a new value and leave the original data unchanged (no mutation), or it can modify the original data directly (mutation). These behave very differently when the same data is used later.
Practice Question
What is displayed after the following code runs?
myList ← [10, 20, 30]
REMOVE(myList, 1)
DISPLAY(myList[1])REMOVE(myList, 1) removes the element at index 1, which is 10. The remaining elements shift down: the list becomes [20, 30]. Now myList[1] is 20.
A) The value 10 was removed from the list and no longer exists in it. C) After removal, 30 is at index 2, not index 1. D) The list still has two elements, so accessing index 1 is valid.
Students forget that removing an element causes all subsequent elements to shift down by one index position. They may think the indices stay the same with a gap.
After any REMOVE or INSERT operation, redraw the list with updated values and indices before answering questions about element positions.
Keep Practicing!
Consistent daily practice is the key to AP CSP success.
AP CSP Resources Get 1-on-1 Help