- Data types in Python
- Sorting list/tuple/dictionaries
- Dictionary in Python
- What can we use as a key in dict?
- Hashing and hash functions
- Collections
- String formatting
- Resources
Data types in Python
- Mutable and immutable types?
- Mutable and immutable types as function argument?
- When mutable is argument to function → python does call by object reference.
- Immutable object → python “switches” to call by value (creates a new string object to hold the newly created object).
- Coding exercises
Mutable — points to the same object id() | Immutable — creates new object when we modify |
list | None |
set | bool: True, False |
dict | int, float |
bytearray | str |
tuple | |
frozenset | |
bytes (integer in range 0 ≤ x ≤ 255) |
‣
Sorting list/tuple/dictionaries
dict(sorted(count_dict.items(), key=lambda x:x[1]))
Dictionary in Python
Python dicts are hash tables. Keys can be None, and keys should consist of immutable objects. Each row takes up 24 bytes.
- If there is a collision, Python uses open addressing.
- After 5 key-values are stored, when adding another key-value pair, the probability of hash collisions is too large, so the dictionary is doubled in size. It now takes 240 bytes of memory.
- The common strategies to resolve collisions in a hash table are:
- Open addressing - if the bucket you should use is busy, you just keep searching for a new bucket to be used, when deleting collided element will be also deleted.
- Separate chaining - diving into buckets.
‣
What can we use as a key in dict?
‣
Hashing and hash functions
‣
‣
hashable()Collections
namedtupes, defaultdicts, Counter
String formatting
d Decimal integer
b Binary integer
x Hexadecimal integer
f Float as [-]m.dddddd
e Float as [-]m.dddddde+-xx
g Float, but selective use of E notation
s String
c Character (from integer)
:>10d Integer right aligned in 10-character field
:<10d Integer left aligned in 10-character field
:^10d Integer centered in 10-character field
:0.2f Float with 2 digit precisionResources
- Mutable and immutable, call by reference and call by value
- https://medium.com/@307/mutable-and-immutable-objects-in-python-11412474b253
- https://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference
- Dictionary