Here is a list of Python Tips and Tricks for beginners that aimed to optimize code and reduce coding efforts. All these tips can help you minify the code and optimize execution. Each trick has an example given with a brief explanation.
Tip 1 : Reverse a String in Python
Example : a = "techinputs" print "Reverse is", a[ : : -1 ] Output : stupnihcet
Tip 2 : Combining Multiple Strings
Example : cms = ['I', 'Like', 'Python', 'Coding'] print ' '.join(cms) Output : I Like Python Coding
Tip 3 : Swap of two Numbers
Example : x = 10 y = 15 print(x, y) x, y = y, x print(x, y) Output : (10,15) (15,10)
Tip 4 : Transposing a Matrix
Example : A = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] zip(*A) Output : [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Tip 5 : Storing Elements Of A List Into New Variables
We can use a list to initialize a no. of variables. While unpacking the list, the count of variables shouldn’t exceed the no. of elements in the list.
Example : List = [ 1, 2, 3 ] a, b, c = List print(a, b, c) Output : (1, 2, 3)
Tip 6 : Dictionary/Set Comprehensions
Like we use list comprehensions, we can also use dictionary/set comprehensions.
Example : Dict = {i: i * i for i in xrange(10)} Set = {i * 2 for i in xrange(10)} print(Dict) print(Set) Output : {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
Tip 7 : Create A Dictionary From Two Related Sequences
Example : t1 = (1, 2, 3) t2 = (10, 20, 30) print(dict (zip(t1,t2))) Output : {1: 10, 2: 20, 3: 30}
Tip 8 : Use Interactive “_” Operator
In the Python console, whenever we test an expression or call a function, the result dispatches to a temporary name, _ (an underscore).
Example : >>> 7 + 2 9 >>> _ 9 >>> print _ 9
The “_” references to the output of the last executed expression.
Tip 9 : Use Of Ternary Operator For Conditional Assignment
Example : def smallest(a, b, c): return a if a <= b and a <= c else (b if b <= a and b <= c else c) print(smallest(2, 1, 2)) print(smallest(2, 3, 3)) print(smallest(3, 3, 4)) print(smallest(6, 5, 4)) Output : 1 2 3 4
Tip 10 : Unpack Function Arguments Using Splat Operator
Example : def sample(x, y, z): print(x, y, z) Dict = {'x': 1, 'y': 2, 'z': 3} List = [10, 20, 30] sample(*Dict) sample(**Dict) sample(*List) Output : x y z 1 2 3 10 20 30
Tip 11: Use A Dictionary To Store A Switch
Example : stdcalc = { 'sum': lambda a, b: a + b, 'subtract': lambda a, b: a - b } print(stdcalc['sum'](7,4)) print(stdcalc['subtract'](7,4)) Output : 11 3
Tip 12: Most Frequent Value in a List
Example : test = [0,1,2,3,1,1,2,0,3,3,3] print(max(set(test), key=test.count)) Output : 3