Python Slots Vs Dict
There are quite a few data structures available. The builtins data structures are: lists, tuples, dictionaries, strings, sets and frozensets.
Lists, strings and tuples are ordered sequences of objects. Unlike strings that contain only characters, list and tuples can contain any type of objects. Lists and tuples are like arrays. Tuples like strings are immutables. Lists are mutables so they can be extended or reduced at will. Sets are mutable unordered sequence of unique elements whereas frozensets are immutable sets.
Lists are enclosed in brackets:
Dictfromclass ¶ In this section we define a functions that gets a dictionary from a class. This dictionary contains all the information supplied in the body of a class statement, except for the doc-string. First, Python looks inside of the locals array, which has entries for all local variables. Python works hard to make local variable lookups fast, and this is the only part of the chain that doesn’t require a dictionary lookup. If it doesn’t exist there, then the globals dictionary is searched.
Tuples are enclosed in parentheses:
Tuples are faster and consume less memory. See Tuples for more information.
Python Dict Vs Set
- slots Magic. In Python every class can have instance attributes. By default Python uses a dict to store an object’s instance attributes. This is really helpful as it allows setting arbitrary new attributes at runtime. However, for small classes with known attributes it might be a bottleneck. The dict wastes a lot of RAM.
- Instead of having a dynamic dict that allows adding attributes to objects dynamically, slots provide a static structure which prohibits additions after the creation of an instance. When we design a class, we can use slots to prevent the dynamic creation of attributes. To define slots, you have to define a list with the name slots. The list has to contain all the attributes, you want to use.
- By default Python uses a dict to store an object’s instance attributes. This is really helpful as it allows setting arbitrary new attributes at runtime.
Python Dict Iterate
Dictionaries are built with curly brackets:
Sets are made using the set() builtin function. More about the data structures here below:
There are additional data structures available in the collections and heapq modules for instance.