Are dictionaries mutable5/6/2023 ![]() The append and _delitem_methods must raise the RuntimeError exception (see the import) from builtins, when they are called while the ListSI is being iterated over.This_init_ method, and other dunder methods in the ListsI class is already written. To add to a list you can use the append() method, passing whatever you want added as an argument in parentheses. Objects constructed from the ListsI class store 2 attributes: a real list (_real_list) and a count of the number of (nested) iterations in which this ListsI is being iterated on Liter_count). Lists are mutable, so items can be modified. Iterating over a list should leave the list unchanged. Because we know this order for a list we can determine how values added or deleted will be treated in the iteration but we cannot determine this information for a set or dict, so mutating it is prohibited Write a list-like class (implementing some, but not all, list operations) named ListSI (SI stand for Special Iterator) that raises a RuntimeError exception when executing code that attempts to change the length of a list (with append and del) while the list is being iterated over, mostly think iteration by a for loop, but also if _iter_ is called explicitly: i = iter (aListSI), print (next(i)). When Python runs the following code S = set () for i in s: s.add(2) # this line raises: RuntimeError: Set changed size during iteration Why does Python allow us to change list sizes during iteration but not set/dict sizes? The rationale relates to the fact that we know what order the values in a list are iterated over, but not a set/dict. Although we can execute code that changes the length of a list while it is being iterated over (by calling append or del), Python does not allow us to change the lengths of a set or dict while either is being iterated over. However, it is not indexed by a sequence. It is similar in spirit to List, Set, and Tuples. A word of caution: you can use only immutable values (like strings) for keys of a dictionary but you can use either immutable or mutable values for values. ![]() (4 pts) Lists, sets, and dictionaries are all mutable. Dictionary is a built-in Python Data Structure that is mutable.
0 Comments
Leave a Reply. |