Cheatsheet Python A4
Cheatsheet Python A4
Name Comment
Python Global Interpreter Lock For Garbage Collection. A mutex controls of the global Python interpreter
Python tuples VS lists tuple is immutable
Python nonlocal VS global Github: cheatsheet-python-A4/code/varNonlocalGlobal.py
Python For VS While Loops The for statement is used to iterate over the elements of a sequence
subprocess.run VS os.system In Linux, launch processes through shell or os.execvp
single quote VS double quote Generally double quotes for string; single quotes for regexp, dict keys, or SQL
Common reasons of python memory leak reference cycles, underly libaries/C extensions, lingering large objects not released
Example: Python cycle reference Github: cheatsheet-python-A4/code/exampleCycleReference.py
Passing function as an argument in Python Github: cheatsheet-python-A4/code/funcAsParameter.py
lambda/an anonymous function
Why no support for multi-line comments Link: Python Multi-line Comments
Python callable print(callable(1)), print(callable(lambda: 1))
Python long
Python Constants vs Literals
How functools.lrucache works
Python yield
Reference Link: Python Design and History FAQ
GitHub: https://github.com/dennyzhang/cheatsheet-python-A4 1 of 7
Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-python-A4 Updated: June 22, 2020
GitHub: https://github.com/dennyzhang/cheatsheet-python-A4 2 of 7
Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-python-A4 Updated: June 22, 2020
1.4 String
Name Comment
Reverse string ’hello world’[::-1]
Array to string ’ ’.join([’a’, ’b’])
Integer array to string ’ ’.join([str(v) for v in [1, 2, 3]])
Split string to array "hello, python".split(",")
String to array list(’abc’)
Format to 2 digits print "%02d" % (13)
Capitalize string ’hello world’.capitalize()
Upper/lower string ’aBc’.upper(), ’aBc’.lower()
Check if string represent integer ’123’.isdigit()
Check if string alphabetic ’aBc’.isalpha()
Check if string alphanumeric ’a1b’.isalnum()
Count substring ’2-5g-3-J’.count(’-’)
Remove tailing ’0’ ’0023’.rstrip(’0’)
Remove leading ’0’ ’0023’.lstrip(’0’)
Trip a string ’ Hello ’.strip()
Find location of substring ’abc’.find(’d’)= (returns -1)
Find location of substring ’abc’.index(’d’)= (raise exception)
Check whether substring "el" in "hello world"
Replace string ’ab cd’.replace(’’,”)
Padding leading zero ’101’.zfill(10)
Padding whitespace to the left ’a’.ljust(10,’=’)
Padding whitespace to the right ’a’.rjust(10,’=’)
Format string "%s,%d,%s" % ("2012", 12, "12")
GitHub: https://github.com/dennyzhang/cheatsheet-python-A4 3 of 7
Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-python-A4 Updated: June 22, 2020
1.9 Integer
Name Comment
max, min sys.maxsize, -sys.maxsize-1
min, max min(2, 3), max(5, 6, 2)
min with customized comparision min(a, b, key=lambda x: x*x-2*x+1)
generate range for num in range(10,20)
get ascii ord(’a’), chr(97)
print integer in binary "{0:b}".format(10)
GitHub: https://github.com/dennyzhang/cheatsheet-python-A4 4 of 7
Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-python-A4 Updated: June 22, 2020
1.12 File
Name Comment
Append file open("/tmp/test.txt", "ab").write("\ntest:")
Write file open("/tmp/test.txt", "wab").write("\ntest:")
Read files f.readlines()
Check file os.path.exists("/tmp/test.txt")
Reference Github: cheatsheet-python-A4/code/exampleFile.py
1.13 Math
Name Comment
sqrt import math; math.sqrt(5)
power import math; math.pow(2, 3)
log import math; math.log(5, 2), log2(5)
random random.randint(1, 10) 1 and 10 included
eval string eval("2-11*2")
1.14 Networking
Name Comment
Send http REST call pip install requests; r = requests.get(’https://XX/XX’, auth=(’user’, ’pass’))
Start a simple HTTP server python -m SimpleHTTPServer <port_number>
1.16 Queue/heapq
Name Comment
Initialize min heap heapq.heapify(q)
heappush a tuple q=[]; heapq.heappush(q, (5, ’ab’))
pop print (heapq.heappop(q))
first item q[0]
print heapq print list(q)
create a queue from collections import deque; queue = deque([1,5,8,9])
append queue queue.append(7)
pop queue from head element = queue.popleft()
Reference Link: Python Heapq
# initializing list
li = [5, 7, 9, 1, 3]
GitHub: https://github.com/dennyzhang/cheatsheet-python-A4 5 of 7
Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-python-A4 Updated: June 22, 2020
heapq.heappush(li,4)
print (list(li))
• Print linkedlist
nums = [3, 2, 6]
def myCompare(v1, v2):
return -1
sorted_nums = sorted(nums, cmp=myCompare)
print nums # [3, 2, 6]
print sorted_nums # [6, 3, 2]
GitHub: https://github.com/dennyzhang/cheatsheet-python-A4 6 of 7
Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-python-A4 Updated: June 22, 2020
col_count, row_count = 3, 2
matrix = [[None for j in range(col_count)] for i in range(row_count)]
print matrix
GitHub: https://github.com/dennyzhang/cheatsheet-python-A4 7 of 7