Best Python Tips and Tricks
1.Swap: You can swap value of a and b in just one line using: a,b=b,a 2.Reverse a string: my_str="hello" rvrse=my_str[::-1] Output:"olleh" 3.Rotate list by n: l[-n:]+l[:-n] e.g l=[1,2,3,4,5] a=l[-2:]+l[:-2] Output: a=[4, 5, 1, 2, 3] 4.Del all elements of list: lst = [1, 2, 3, 4, 5] del lst[:] Output: lst=[] 5.List comprehension: vals = [expression for value in collection if condition] even_squares = [x * x for x in range(10) if not x % 2] even_squares>>>[0, 4, 16, 36, 64] 6.'==' vs 'is' e.g a = [1, 2, 3] b = a a == b>>>True a is b>>>True But , c = list(a) a==c>>>True a is c>>>False 7.sort() vs sorted: sort() modifies the original list in place. The return value is None. sorted() returns a new list. 8.collections.Counter lets you find the most commonelements in an iterable: E.g; import collections c = collections.Counter('helloworld') c>>>Counter({'l': 3, 'o': 2, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1}) c.most_common(3)>>>[('l', 3), ('o', 2), ('e', 1)] 9.Find permutation using itertools. E.g; import itertools for p in itertools.permutations('ABCD'): print(p) Note:itertools.combinations can be used for finding combinations. 10.Importing everything from a module: from <module_name> import * 11.Find factorial by: import math math.factorial(x) P.S. During editing some points were deleted by accident.As I have no saved copy of this it will take some time to find them again.