Things need to be noticed for python (2)

tan21098
4 min readSep 22, 2020

1, the performance of append, extend, and +=

P(append) > P(extend) > P(+=)

For extend, extend the right type will reduce the cognitive load

The lower one is preferred to the upper one

2,List Copy

“=”: assign the address of the old list to the new list. So change on the new list will also be the change on the old list.

copy with assign symbol

“. copy()”: create the same values in a new address. So changing the new list will not modify the new list.

copy with copy method

3, Boolean as Dictionary key

When we use True or False as dictionary keys, notice that they will be converted to 1 and 0.

This is because the boolean class is a subclass of the integer class.

boolean is a subclass of integer

But we can use a string ‘True’ as a dictionary key.

4, Methods in place

The methods listed below modify the object directly(in place), they do not create a new object, so they do not have return values. Do not assign them to a new object.

.sort()
.update()
.append()
.add()
Do not print or assign
call the method and print the variable

5, Tuples are defined with commas

Q: How to create a tuple with only one item?

A: Use comma!

parentheses do not work
commas work!
you may ignore parentheses

6, Hashable

Hashable means a hash value never changes during its lifetime.

All built-in immutable types are hashable

numbers
strings (both unicode and bytes)
tuple

Mutable ones are not hashable

list
dict
set

Tuple Element/Set Element/Dict Key need to be hashable

7, Dictionary Key & Value loop

Note dict.keys() is not a list

for i in dict():          --> i is key
for i in dict.keys() --> i is key
for j in dict.values() --> j is value
for i, j in dict.items() --> i, j is key, value

8, Sort with key

sorted(list, key=len)           <-- we can choose to sort by length
sorted(list, key=lambda i, i*i) <-- we can customize the funtion

9, Map, Filter and Reduce

They are all lazy, they only promise to do but not really execute unless you cast them onto a list or some container.

Map:map(func, *iterables) --> map objectMake an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.

Notice that you can give no function to filter method

Filter:filter(function or None, iterable) --> filter objectReturn an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true. 

Notice reduce method is not a built-in function. Reduce method always returns a single value.

Reduce:reduce(function, sequence[, initial]) -> valueApply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value.

10, Limitation of Lambda

lambda cannot take assignments or use statements (while, try, …)

lambda are pure expressions so can only be simple functions.

11, Dict method

dict.get(“find”,”cant find”)

dict.update()

1, Pass keyword arguments.update(California='Sacramento')2, Pass another dict.update({'California': 'Sacramento'})3, Pass a sequence with paired data.update([['California','Sacramento']])

return None if not find by default

dict.Counter().most_common(n=2)

12, Sort Dictionary

Sort by keysorted(d.items())Sort by valuedict(sorted(d.items(), key=lambda x: x[1]))

--

--