- Key Concepts
- Swap 2 Elements in a List
- The List Count Method
- Use Dict as a Histogram
- Zip 2 Lists into a Dictionary
- Check if a Float is a Whole Number
- Get the Index of the Min/Max Value in a List S
- Import .py File as Module
- Initialize a 2D Array (Nested List)
- Flatten a 2D Array
- Find Min/Max in 2D Nested List
- To Check a List of Booleans to Yield a Boolean: all(), any()
- If-Else in List Comprehension
- Create Dict with Keys from a Set or List
- Using Lists as Stacks
- Using Lists as Queues
- A Peculiar Usage of Augment Assignment in Python
- Class Method vs. Static Method
- 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
- byte array
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
listdata structure in Python has a method
list.count(element)which takes O(n) time.
- Can be high dimensional list, e.g.
- Side note:
set(2DList) => 1DSet
- Side note:
- If we want all counts, using a
dictas 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 % 1 == 0
- The second one works because in Python,
5.5 % 1 = 0.5,
5.0 % 1 = 0.0, and
0.0 == 0is
Get the Index of the Min/Max Value in a List S
- If there are duplicates, these methods return the first occurrence
float('inf')is positive inf,
- 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)
- Closure: http://en.wikipedia.org/wiki/Closure_%28computer_programming%29
- Pass function as parameter into another function.
- 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] * consthas 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]
Find Min/Max in 2D Nested List
To Check a List of Booleans to Yield a Boolean: all(), any()
- Beware, DO NOT use it like
all([2, 2, 2]) == 2,
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]
What about elif??
- To initialize a 2D (4*4) list f where
f[i] = i, f[j] = j, else 0:
- [expr if i == val else expr if j == val else expr for i in iterable]
- very powerful pythonic list comprehension!!
Create Dict with Keys from a Set or List
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
@staticmethodfunction 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.
@classmethodfunction also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance. That’s because the first argument for
@classmethodfunction must always be cls (class).
To be continued…