0% found this document useful (0 votes)
10 views

20 Valuable and Essential Python Hacks For Beginners - by Vivek Coder - Better Programming - Aug, 2020 - Medium

This document provides 20 Python programming hacks and tricks for beginners. Some of the tricks covered include value swapping with one line of code, joining a list of strings into one string, finding the most common element in a list, testing if two strings are anagrams, reversing a string or list, transposing a matrix, chained comparisons, using dictionary get method, sorting dictionaries by value, list comprehensions, timing code execution, and merging dictionaries. The tricks provide concise and useful code snippets for performing common tasks in Python.

Uploaded by

Pablo Ferraz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

20 Valuable and Essential Python Hacks For Beginners - by Vivek Coder - Better Programming - Aug, 2020 - Medium

This document provides 20 Python programming hacks and tricks for beginners. Some of the tricks covered include value swapping with one line of code, joining a list of strings into one string, finding the most common element in a list, testing if two strings are anagrams, reversing a string or list, transposing a matrix, chained comparisons, using dictionary get method, sorting dictionaries by value, list comprehensions, timing code execution, and merging dictionaries. The tricks provide concise and useful code snippets for performing common tasks in Python.

Uploaded by

Pablo Ferraz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

This is your last free story this month. Upgrade for unlimited access.

20 Valuable and Essential Python Hacks for


Beginners
A short, useful guide for quick and e cient Python

Vivek Coder Follow


Aug 6 · 5 min read

Photo by Christian Wiediger on Unsplash

Python is among the most widely used market programming languages in the world.
This is because of a variety of driving factors:

It’s simple to understand.

It’s incredibly versatile.


It contains a broad collection of modules and libraries.

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.

. . .

20 Necessary Python Hacks


1. Swapping values
Number swaps normally involve values storage in temporary variables. Yet we could do
it by using a single line of code through this Python tip, with no transient variables.

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

ValueSwapping.py hosted with ❤ by GitHub view raw

2. One string of all items within a list


When you have to convolve a string list, you could do this one after another through
updating each item with the help of a for loop. It will, nevertheless, be cumbersome,
particularly if the list has been lengthy. Within Python, strings are immutable. Thus, in
each duo of concatenation, the left and right strings should be copied into a fresh string.

Using a join() function, as seen here, is a cleaner solution:

p = ["Python", "is", "a", "popular", "language"]


print(" ".join(p))

output
Python is a popular language

3. Most common element in the list


Identify the most frequently occurring value in a list. If various items occur equally print
one of them.
Create a list set to remove the redundant values. So the maximum number of events of
each item is found in the set, and then we consider the maximum.

list1 = [0, 1, 2, 3, 3, 2, 3, 1, 4, 5, 4]
print(max(set(list1), key = list1.count))

output
3

4. Test if two strings are anagrams

1 def anagram(string_1, string_2):


2 """Test if the strings are anagrams.
3 string_1: string
4 string_2: string
5 returns: boolean
6 """

Anagrams.py hosted with ❤ by GitHub view raw

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.

1 from collections import Counter


2 def anagram(string_1, string_2):
3 return Counter(string_1) == Counter(string_2)
4 anagram('pqrs','rqsp')
5 True
6 anagram('pqrs','rqqs')
7 False

Anagrams.py hosted with ❤ by GitHub view raw

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

Slicing.py hosted with ❤ by GitHub view raw


6. Reverse a list
A copy of the list is created from this approach, and as well, the list is not sorted in order.
To create a copy, you need more room to hold all the existing elements.

1 # using slicing approach


2 def Reverse(lst):
3 lst1 = lst[::-1]
4 return lst1
5
6 lst = [5, 6, 7, 8, 9, 10]
7 print(Reverse(lst))
8 output
9 [10, 9, 8, 7, 6, 5]

ReverseList.py hosted with ❤ by GitHub view raw

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)

TransposeMatrix.py hosted with ❤ by GitHub view raw

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:
{.....}

Comparisons return boolean values True or False .

See the example below:

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

ChainedCompare.py hosted with ❤ by GitHub view raw

9. Dictionary ‘get’
Below is a traditional way of accessing a value for a key in Python dictionaries.

dict = {"P":1, "Q":2}


print(dict["P"])
print(dict["R"])

The concern is that the third line of the code yields a key error:

Traceback (most recent call last):


File ".\dict.py", line 3, in
print (dict["R"])
KeyError: 'R'
To prevent these cases, the get() function is used. This technique provides the value for
a specific key when available in the dictionary. when it isn’t, None will be returned (if
only one argument is used with get()) .

1 dict = {"P":1, "Q":2}


2 print(dict.get("P"))
3 print(dict.get("R"))
4 print(dict.get("R","Unavailable! "))
5 output
6 1
7 None
8 Unavailable!

DictGet.py hosted with ❤ by GitHub view raw

10. Sort dictionary by value


Sorting has always been a useful utility in day-to-day programming. Dictionary in
Python is widely used in many applications, ranging from the competitive domain to the
developer domain.

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)]

DictSort.py hosted with ❤ by GitHub view raw


11. List comprehension
To construct fresh lists from different iterables, list comprehensions are used. Since list
comprehensions yield lists, they contain parentheses that include the expression which
gets executed to every element. List comprehension is simpler, as the Python interpreter
is designed to detect a recurring pattern in looping.

1 # Multiplying each item in the list with 3


2 list1 = [2,4,6,8]
3 list2 = [3*p for p in list1]
4 print(list2)
5 [6,12,18,24]

ListComp.py hosted with ❤ by GitHub view raw

12. Time consumed to implement a part of the program


This one focuses on showing how to compute the time taken by the program or a section
of a program to execute. Calculating time helps to optimize your Python script to
perform better.

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)

Time.py hosted with ❤ by GitHub view raw

13. Merge dictionaries


This is a trick in Python where a single expression is used to merge two dictionaries and
store the result in a third dictionary. The single expression is ** . This does not affect the

other two dictionaries. ** implies that the argument is a dictionary. Using ** is a


shortcut that allows you to pass multiple arguments to a function directly by using a
dictionary.

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.

1 dic1 = {'men': 6, 'boy': 5}


2 dic2 = {'boy': 3, 'girl': 5}
3 merged_dic = {**dic1, **dic2}
4 print(merged_dic)
5 Output
6 {'men': 6, 'boy': 3, 'girl': 5}

MergeDict.py hosted with ❤ by GitHub view raw

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]

Digitize.py hosted with ❤ by GitHub view raw

15. Test for uniqueness


Some list operations require us to test when total items in the list are distinct. This
usually happens when we try to perform the set operations in a list. Hence, this
particular utility is essential at these times.

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

TestUnique.py hosted with ❤ by GitHub view raw

16. Using enumeration


Using enumerators, finding an index is quick when you’re within a loop.
1 sample_list = [4, 5, 6]
2 for j, item in enumerate(sample_list):
3 print(j, ': ', item)
4 Output
5 0 : 4
6 1 : 5
7 2 : 6

FindIndex.py hosted with ❤ by GitHub view raw

17. Evaluate the factorial of any number in a single line


This one gives you a method to find the factorial of a given number in one line.

1 import functools
2 fact = (lambda i: functools.reduce(int.__mul__, range(1,i+1),1)(4)
3 print(fact)
4 Output
5 24

Factorial.py hosted with ❤ by GitHub view raw

18. Return several functions’ elements


This function is not offered by numerous computer languages. For Python, though,
functions yield several elements.

Kindly review the following instance to understand how it performs.

1 # function returning several elements.


2 def a():
3 return 5, 6, 7, 8
4 # Calling the above function.
5 w, x, y, z= a()
6 print(w, x, y, z)
7 Output
8 5 6 7 8

SevFunctElements.py hosted with ❤ by GitHub view raw

19. Incorporate a true Python switch-case statement


Below is the script used to replicate a switch-case structure with a dictionary.

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

SwitchCase.py hosted with ❤ by GitHub view raw

20. With splat operator unpacking function arguments


The splat operator provides an efficient way of unpacking lists of arguments. For
clarification, please go through the following illustration:

1 def test(a, b, c):


2 print(p, q, r)
3 test_Dic = {'a': 4, 'b': 5, 'c': 6}
4 test_List = [10, 11, 12]
5 test(*test_Dic)
6 test(**test_Dic)
7 test(*test_List)
8 #1-> p q r
9 #2-> 4 5 6
10 #3-> 10 11 12

Splat.py hosted with ❤ by GitHub view raw

. . .

The Ending Note


I hope the aforementioned 20 necessary Python hacks will allow you to accomplish your
Python jobs swiftly and effectively. You can further consider those or your assignments
and programs.

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.

Thanks for reading!

Thanks to Yenson Lau and Zack Shapiro.

Programming Python Python3 DevOps Data Science

About Help Legal

Get the Medium app

You might also like