20 Valuable and Essential Python Hacks For Beginners - by Vivek Coder - Better Programming - Aug, 2020 - Medium
20 Valuable and Essential Python Hacks For Beginners - by Vivek Coder - Better Programming - Aug, 2020 - Medium
Python is among the most widely used market programming languages in the world.
This is because of a variety of driving factors:
The brevity and higher readability make it quite prominent among all developers.
As a vital part of my job as a data scientist, I use Python every day. Along the way, I’ve
gained a few amazing hacks. I’ve listed some of those below.
. . .
1 """value swapping"""
2 a, b= 5, 10
3 print(a, b)
4 a, b= b, a
5 print(a, b)
6 output
7 10, 5
output
Python is a popular language
list1 = [0, 1, 2, 3, 3, 2, 3, 1, 4, 5, 4]
print(max(set(list1), key = list1.count))
output
3
Solve the problems above to figure out whether two strings are anagrams. Given two
strings string_1 and string_2 , test if both the strings are anagrams of each other.
5. Reverse a string
Slicing is a handy tip in Python which can also be used to reverse the sequence of items
within a string.
1 # with slicing
2 str = "PQRST"
3 reverse_str = str[::-1]
4 print(reverse_str)
5 Output
6 TSRQP
7. Transpose a matrix
Transposing a matrix means transforming columns to rows and vice versa. With Python,
you can unzip a list that is a transpose of the matrix by using the following code with the
zip function in combination with the * tool.
1 mat=[(5,6,7),(8,9,10),(11,12,13),(14,15,16)]
2 for row in mat:
3 print(row)
4 print("\n")
5 t_mat = zip(*mat)
6 for row in t_mat:
7 print(row)
8 output
9 (5, 6, 7)
10 (8, 9, 10)
11 (11, 12, 13)
12 (14, 15, 16)
13 (5, 8, 11, 14)
14 (6, 9, 12, 15)
15 (7, 10, 13, 16)
8. Chained comparison
In programming, it is quite normal to test more than two conditions. Let’s assume that
we need to test the following:
p < q< r
There is indeed a smarter process of writing it with comparison chaining in Python. The
operator chaining has been represented as below:
if p< q< r:
{.....}
1 # chaining comparison
2 a = 3
3 print(1 < a< 10)
4 print(5 < a< 15)
5 print(a < 7< a*7 < 49)
6 print(8 > a<= 6)
7 print(3 == a> 2)
8 output
9 True
10 False
11 True
12 True
13 True
9. Dictionary ‘get’
Below is a traditional way of accessing a value for a key in Python dictionaries.
The concern is that the third line of the code yields a key error:
Construct a dictionary, as well as show all keys in alphabetical order. List both the
alphabetically sorted keys and values by the value.
1 def dict():
2 keyval ={}
3 # Initializing the value
4 keyval[3] = 48
5 keyval[2] = 6
6 keyval[5] = 10
7 keyval[1] = 22
8 keyval[6] = 15
9 keyval[4] = 245
10 print ("Task 3:-\nKeys and Values sorted",
11 "in alphabetical order by the value")
12 # Remember this would arrange in aphabetical sequence
13 # Convert it to float to mathematical purposes
14 print(sorted(keyval.elements(), key =
15 lambda k_val:(k_val[1], k_val[0])))
16 def main():
17 dict()
18
19 if __name__=="__main__":
20 main()
21 output
22 [(2, 6), (5, 10), (6, 15), (1, 22), (3, 48), (4, 245)]
1 import time
2 initial_Time = time.time()
3 # Program to test follows
4 x, y= 5,6
5 z = x+ y
6 # Program to test ending
7 ending_Time = time.time()
8 Time_lapsed_in_Micro_sec = (ending_Time- initial_Time)*(10**6)
9 print(" Time lapsed in micro_seconds: {0} ms").format(Time_lapsed_in_Micro_sec)
Using this, we first pass all the elements of the first dictionary into the third one and
then pass the second dictionary into the third. This will replace the duplicate keys of the
first dictionary.
14. Digitize
Here is the code that uses map() , list comprehension, and a simpler approach for
digitizing.
1 number = 2468
2 # with map
3 digit_list = list(map(int, str(number)))
4 print(digit_list)
5 [2, 4, 6, 8]
6 # with list comprehension
7 digit_list = [int(a) for a in str(number)]
8 print(digit_list)
9 [2, 4, 6, 8]
10 # Even simpler approach
11 digit_list = list(str(number))
12 print(digit_list)
13 [2, 4, 6, 8]
1 def uniq(list):
2 if len(list)==len(set(list)):
3 print("total items are unique")
4 else:
5 print("List includes duplicate item")
6 uniq([0,2,4,6])
7 total items are unique
8 uniq([1,3,3,5])
9 List includes duplicate item
1 import functools
2 fact = (lambda i: functools.reduce(int.__mul__, range(1,i+1),1)(4)
3 print(fact)
4 Output
5 24
1 def aswitch(a):
2 return aswitch._system_dic.get(a, None)
3 aswitch._system_dic = {'mangoes': 4, 'apples': 6, 'oranges': 8}
4 print(aswitch('default'))
5 print(aswitch('oranges'))
6 Output
7 None
8 8
. . .
Some I found while browsing the Python Standard Library docs. A few others I found
searching through PyTricks.
If you think I should include more or have suggestions, please do comment below.