Python cheat sheet

titile image

Background:

I have been using Python intensively for about 1 year. From now and then I look up some of the common operations and I decided to record all the code snippets in a handbook.

Table:

No. Goal Solution Note
1 Reverse a string or a list  
2 Join a list of strings to a single string  
3 Flatten list from list of list  
4 Trim a string  
5 String replace a substring pattern with another substring  
6 Cast float or string to int auto floor to the nearest integer
7 Check string or char is in uppercase  
8 If statement in list comprehension  
9 If else statement in list comprehension  
10 Transpose matrix (2-d array)  
11 Rotate matrix (2-d array) 90° clockwise if you want to do it inplace, do:
matrix[:] = [list(i) for i in zip(*matrix[::-1])]
12 Check whether str1 is substring of str2  
13 Get Current work directory  
14 Iterate dictionary  
15 Split string with multiple delimiters  
16 Merge 2 dictionaries new value is the sum of 2 values from 2 dictionaries
17 Initialize list with same primitive values don’t use this with 2-d array
18 Python supports tertiary operator  
19 Sort a list of strings by length  
20 String split by keep the delimiters just add outer ( ) to the delimiters
21 Sort dictionary by values if want to sort by keys, change itemgetter(1) to itemgetter(0)
22 Print 2-d array in a better format  
23 Find index and last index of char in string  
24 Find index and last index of item in list  
25 Automatically initialize for new key in dictionary input of defaultdict should be callable, and takes no arguments
26 Get arbitrary one element from set  
27 Remove element at index 2 from the list if no argument, last one is removed
28 Find locations (start, end) of matches with regular expression  
29 Update each value in a dictionary with an operation  
30 Find nth occurrence of b in string a  
31 Find all indices of an element in a list  
32 Return a random element from a list  
33 Product of all elements of a list  
34 Lexicographical  compare of strings “abcd” > “ab” and “ad” > “ab”
35 Integer division round down
36 Two’s complement equals to -1315
37 Padding spaces to a string to a certain length  
38 Get a random float  
39 Get a random integer from range  
40 Get profile of program, print out most time consuming function calls  
41 Get line by line time execution in jupyter notebook need to specify the function name (e.g. totalNQueens) and the real execution call (e.g. totalNQueens(13))should use “” when passing strings as arguments
42 Usage of doctest there must be at least 1 space on the right side of »>
43 Double-ended queue can be think of a queue + stack
44 Printout nicely print out in sorted order
45 Permutation and combination output: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
46 Get all attributes and their values of an object  
47 Get the representation string of the object if not specified, it will be like:’<main.Duck object at 0x00000133BDE7A6D8>’
48 Save memory by using generator instead of list instead of sum([x*x for x in range(10)])
49 Variables created inside a loop are accessible outside the loop scope thej actually is assigned the last element of the list mylist
50 Check whether a list iterate till end normally  
51 To make class objects comparable, just add function __lt__  
52 Sort a list of list by multiple values  
Written on May 24, 2018