### Key Concepts

• Immutable = hashable = can be element of a set (or key of dict)
• mutable = unhashable = cannot be element of a set (or key of dict)

• immutables in Python:
• int, float, long, complex
• str
• tuple
• bytes
• frozenset
• mutables
• byte array
• list
• set
• dict
• Do not modify an container while looping over it. Create a copy and loop on that.

• DO NOT ASSIGN STRING CHAR AS IN LIST!!!
• list(string), modify, and ‘’.join(list) to get string back
• To sort a string:
• An example of function:

### Swap 2 Elements in a List

• Usually in all languages it looks like,
• In Python it can be as simple as A[i], A[j] = A[j], A[i]!

### The List Count Method

• The list data structure in Python has a method list.count(element) which takes O(n) time.
• Can be high dimensional list, e.g. board[:m][:n].count(element).
• Side note: set(2DList) => 1DSet
• If we want all counts, using a dict as a histogram gives all counts in one pass.

### Use Dict as a Histogram

• Don’t forget to check if key exists.
• A better way, use dict.get(key, default=None).
• default – This is the Value to be returned in case key does not exist.

### Zip 2 Lists into a Dictionary

• zip two lists into a list of tuples
• dict the list of tuples into a dictionary: note, the tuples must have length 2, error if 3
• an easy way of constructing a reversed dictionary

### Check if a Float is a Whole Number

• Two methods: (my_float).is_integer(), or my_float % 1 == 0
• The second one works because in Python, 5.5 % 1 = 0.5, 5.0 % 1 = 0.0, and 0.0 == 0 is True.

### Get the Index of the Min/Max Value in a List S

• If there are duplicates, these methods return the first occurrence

### Infinity

• float('inf') is positive inf, float('-inf') is negative
• Be careful not to multiply inf by 0, it yields nan

### Import .py File as Module

• In Python, modeling a clustering as a set of sets is impossible since the elements of a set must be immutable.
• Import self-defined module: put the file.py file into the same directory, and do
• import module (as alias)

### Lambda

• runtime function with no name
• often used in conjunction with filter(), map(), reduce()
• Or pass a small function as argument

### Initialize a 2D Array (Nested List)

• USE LIST COMPREHENSION!
• DO NOT USE [[None] * ncol] * nrow]! [anything] * const has sublists pointing to the same object.
• Similarly, to initialize a triangle where ncol <= nrow:
• don’t forget the nrow+1
• To initialize a contant 2D(or even higher dimensional) list with the shape of a given list “tri”
• To initialize a 2D list f1 where the value of the first row is 0 to j and the first col is 0 to i. The commas and colons should be removed, just to make it more readable.

### Flatten a 2D Array

• sublist in matrix, then, item in sublist.
• Nested loops in List Comprehension: outer loop first, then inner loop.
• flatten = [item for sublist in matrix for item in sublist]

### To Check a List of Booleans to Yield a Boolean: all(), any()

• Beware, DO NOT use it like all([2, 2, 2]) == 2, all() and any() are for booleans inside.

### If-Else in List Comprehension

• To initialize a list f from list S, if S[i] == 0, f[i] = 1, else f[i] = 0. Here is a 2D example:
• [expr if S[] == val else expr for i in iterable]

• To initialize a 2D (4*4) list f where f[i][0] = i, f[0][j] = j, else 0:
• [expr if i == val else expr if j == val else expr for i in iterable]
• very powerful pythonic list comprehension!!

### Using Lists as Stacks

• It’s very easy to use lists as stacks with append() and pop(). Last in first out.

### Using Lists as Queues

• We can use pop(0) and append() to implement the queue behavior but it’s not efficient. Because popping from the first position is slow, all elements must shift. Instead it’s better to use collections.deque and its append() and popleft() methods.

### A Peculiar Usage of Augment Assignment in Python

• The augmented addition operator += behaves unexpectedly in the following case,
• What happened is that += calls iadd() method and try to modify the list in-place, while adding all the elements of the iterable on the right to the list.

### Class Method vs. Static Method

• @staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.

• @classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance. That’s because the first argument for @classmethod function must always be cls (class).

To be continued…