No, this is not an exception. Nothing is assigned to the dictionary view. Views are explicitly documented as being dynamic:
They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.
That's because they only store a reference to the original dictionary and provide you with direct access to just the keys, or just the values, or to (key, value)
pairs in ways that differ from the dictionary API.
You can build your own views onto objects if you wanted, but note that such an object still needs a reference to the original object(s):
from collections.abc import Sequence
class ListReversedView(Sequence):
def __init__(self, lst):
self._lst = lst
def __getitem__(self, idx):
if idx < 0:
new = (-idx) - 1
else:
new = len(self) - idx - 1
if new < 0:
raise IndexError(new)
return self._lst[new]
def __len__(self):
return len(self._lst)
def __repr__(self):
return f"[{', '.join(map(repr, self))}]"
The above example gives you a different view on list contents; changes to the list are reflected in the 'view' this object provides. Nothing special needs to be done to Python's assignment model; assignments are still just references to objects, and the _lst
attribute in this view object is no exception:
>>> foo = ['spam', 'ham', 'eggs']
>>> view = ListReversedView(foo)
>>> view
['eggs', 'ham', 'spam']
>>> foo[-1] = 'bacon'
>>> view
['bacon', 'ham', 'spam']
Circling back to your list loop; you can still assign back to the the list object itself; rebinding names may not work, but rebinding the indices works just fine:
for index in range(len(locs)):
locs[index] = []
In summary, Python objects all live on a heap, and names and attributes are just referencing to those objects. Multiple references can exist, and each such a reference will see changes made to the object (if permitted). Assignment changes only what a specific reference points to. Dict views are no exception here, they just continue to reference the dictionary from which they were created.
You may want to read up on the Python model; I strongly recommend the Facts and myths about Python names and values article by Ned Batchelder.