Week 12: Constant-Time Access

Most of this week was review, but there was still some new content to be learned: constant-time access.  Now surprisingly, Python lists have constant-time access when the index is known.  This is a huge revelation, because access time then does not depend on the size of the list.


It would make sense then, for every other data type, such as dictionaries, to work as a list.  The biggest advantage to dictionaries - which is also a disadvantage of lists - is the presence of immutable keys that don't necessarily have to be integers, making access more 'meaningful'.  In a list of my courses for instance, if I wanted to access my favourite course, I would want to use the term 'favourite' to access that course instead of memorizing an index value associated with it.

Hash tables are useful for this reason.  They turn objects such as strings into integers that can be used as indices for a list.  This also explains to long-standing mystery of why we cant' use immutable objects as keys in dictionaries.  When we create a key, it is hashed into an integer, which is a concrete value.  If we were to change the key so that it resembled another key instead, then we would have 2 of the same object with different hash values.

No comments:

Post a Comment