Python common tips

Modules

Note that from myModule import * shouldn’t be used. If done, all the global variables defined in myModule will appear in the current namespace. Modulus should not pollute each other.

Lists and npArrays

1- Lists are (much) faster than npArrays when accessing or appending elements. However, npArrays are faster when doing linear algebra operations. It is more efficient to manipulate data in the form of lists and then convert them into npArrays when dealing with large data.

Set

1- A set of sets: frozenset()

listOfSets1 = [{5},{1,2},{3,4},{5,7,9}]
listOfSets2 = [{11},{1,2},{12,16},{5,7,9},{7,23,13}]
setOfSets1 = {frozenset(eachSet) for eachSet in listOfSets1}
setOfSets2 = {frozenset(eachSet) for eachSet in listOfSets2}
setOfSets1.intersection(setOfSets2)
Out[0]: {frozenset({5, 7, 9}), frozenset({1, 2})}

Functions

1- Type hinting

def myFunction(text: str, flag: bool, name: str = "Aristotle") -> str:
pass

Operators

1- The results of different operators on objects. Objects (e.g. lists, dictionaries, other class objects, etc.) with the same value are usually stored at separate memory addresses.

L1 = [1,2,3]
L2 = [1,2,3]
print(L1==L2)
print(L1 is L2)
print(L1 is not L2)
L1 = [1,2,3]
L2 = [6,7,8]
print(L1 != L2)
print(L1 is not L2)
# output
True
False
True
True
True

Useful Functions

zip() pair up iterables and gives and iterator (https://realpython.com/python-zip-function/)

I/O

Save an array to a text file.
Method 1: use np.savetxt()