Practice question · Put in order
Order these events so that every stated outcome is true at the moment it is written.
- Append 6 through alias, so data now reads [5, 6]
- Set alias to data, so both names now see [5]
- Set copy to an explicit copy of data, freezing it as [5, 6]
- Set data to the list [5]
- Append 7 to data, so alias now reads [5, 6, 7] while copy still reads [5, 6]
Hints
- Each line states what the names hold at that instant, so only one order makes every line true.
- The copy must be taken at the exact moment the list holds [5, 6], neither before nor after.
Show the answer
- Set data to the list [5]
- Set alias to data, so both names now see [5]
- Append 6 through alias, so data now reads [5, 6]
- Set copy to an explicit copy of data, freezing it as [5, 6]
- Append 7 to data, so alias now reads [5, 6, 7] while copy still reads [5, 6]
Why
Order decides everything here: the copy freezes the list as it was at that instant, so 6 must be appended before the copy and 7 after it. The alias, by contrast, has no such timing, it shares the one list forever, so the final append is visible through both data and alias but not through copy.
Practise State, Mutation, and Side Effects
The app has 7 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.
More questions on State, Mutation, and Side Effects
- A function that writes to a global variable is as easy to test as one that only returns a value, provided…
- A function is called twice with identical arguments and returns a different answer the second time. Select…
- A function sorts the list it is given rather than returning a sorted copy. Why is that worth documenting…
- Sort each statement by whether it concerns the identity of an object or merely its value.