Python Tips & Tricks - 50 Basic & Intermediate Tips & Tricks PDF
Python Tips & Tricks - 50 Basic & Intermediate Tips & Tricks PDF
Method 2
name1 = {"kelly": 23,
"Derick": 14, "John": 7}
name2 = {"Ravi": 45, "Mpho": 67}
names = {**name1, **name2}
print(names)
Output:
{'kelly': 23, 'Derick': 14, 'John': 7, 'Ravi': 45,
'Mpho': 67}
3. Calendar with Python
Did you know that you can get a calendar using Python?
Python has a built-in module called calendar. We can import
this module to print out the calendar. We can do a lot of things
with calendar.
Let’s say we want to see April 2022; we will use the month class
of the calendar module and pass the year and month as
arguments. See below:
import calendar
month = calendar.month(2022, 4)
print(month)
Output:
April 2022
Mo Tu We Th Fr Sa Su
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30
4.Get Current Time
The below code demonstrates how you can get the current time
using the datetime() module. The strftime() method to format
time to the desired output. This code breaks down how you can use
the datetime module with strftime() method to get a formatted
string of time into hours, minutes, and seconds format.
from datetime import datetime
time_now = datetime.now().strftime('%H:%M:%S')
print(f'The time now is {time_now}')
Output:
The time now is 17:53:19
# step one
x ^= y
# step two
y ^= x
# step three
x ^= y
Another way you can do it is using a normal for loop. This is the
naïve way. See below:
list1 = ['John','Kelly', 'Peter', 'Moses', 'Peter']
Using itertools
import itertools
max_num = max(enumerate(x),
key = lambda x: x[1])
print('The index of the biggest num is',
max_num[0])
Output:
The index of the biggest num is 3
max_num = min(enumerate(x),
key = lambda x : x[1])
print('The index of the smallest num is',
max_num[0])
Output:
The index of the smallest num is 0
10.Absolute Value of a Number
Let’s say you have a negative number and you want to return
the absolute value of the number; you can use the abs()
function. The Python abs() function is used to return an
absolute value of any number. Below, we demonstrate how we
can return a list of absolute numbers from a list of numbers that
have negative and positive numbers.
list1 = [-12, -45, -67, -89, -34, 67, -13]
print([abs(i) for i in list1])
Output:
[12, 45, 67, 89, 34, 67, 13]
You can also use abs on floating number and it will return the
absolute value. See below:
a = -23.12
print(abs(a))
Output:
23.12
11.Adding a Thousand Separator
If you are working with big figures and you want to add a
separator to make them more readable, you can use the format()
function. See the example below:
a = [10989767, 9876780, 9908763]
Let’s say you want to return all the names in a list that starts
with ‘a’, here is how you would use startwith() to accomplish
that:
Using startswith()
list1 = ['lemon','Orange',
'apple', 'apricot']
new_list = [i for i in list1 if i.startswith('a')]
print(new_list)
Output:
['apple', 'apricot']
Using Endswith()
list1 = ['lemon','Orange',
'apple', 'apricot']
new_list = [i for i in list1 if i.endswith('e')]
print(new_list)
Output:
['Orange', 'apple']
13.Nlargest and Nsmallest
Let’s say you have a list of numbers and you want to return the 5
largest numbers from that list, or the 5 smallest numbers from a
list. You cannot just use the max() and min() functions because
they only return a single number. There is a Python built-in
module that you can use and will make your life easier. It is called
heapq.
Using Nlargest
import heapq
results = [12, 34, 67, 98, 90, 68, 55, 54, 64, 35]
max_list = heapq.nlargest(5, results)
print(max_list)
Output:
[98, 90, 68, 67, 64]
Using Nsmallest
Import headq
Results =[12, 34, 67, 98, 90, 68, 55, 54, 64, 35]
min_list = heapq.nsmallest(5, results)
print(min_list)
Output:
[12, 34, 35, 54, 55]
14.Checking for Anagram
You have got two strings; how would you go about checking
if they are anagrams?
If you want to check if two strings are anagrams, you can use the
Counter() class from the collections module. Below we are
checking if a and b are anagrams.
from collections import Counter
a = 'lost'
b = 'stol'
print(Counter(a)==Counter(b))
Output:
True
You can also use the sorted() function to check if two strings
are anagrams. See the code below:
a = 'lost'
b = 'stol'
if sorted(a)== sorted(b):
print('Anagrams')
else:
print("Not Anagrams")
Output:
Anagrams
15.Checking Internet Speed
Did you know that you can check internet speed with Python?
There is a module called speedtest that you can use to check the
speed of your internet. You will have to install it using pip.
d_speed = speedtest.Speedtest()
print(f'{d_speed.download()/8000000:.2f}mb')
Output:
213.78mb
up_speed = speedtest.Speedtest()
print(f'{up_speed.upload()/8000000:.2f}mb')
Output:
85.31mb
16.Python Reserved keywords
If you want to know the reserved keywords in Python, you can
use the help() function. Remember, you cannot use any
of these words as variable names. Your code will
generate an error.
print(help('keywords'))
Output:
Here is a list of the Python keywords. Enter any
keyword to get more help.
website = https://www.google.com/
As you can see, lists are more space efficient than sets.
21.Accessing Dictionary Keys
How do you access keys in a dictionary? Below are three
different ways you can access the keys of a dictionary:
try:
iter_check = iter(a)
except TypeError:
print('Object a not iterable')
else:
print('Object a is iterable')
try:
iter_check = iter(b)
except TypeError:
print('Object b is not iterable')
else:
print('Object b is iterable')
Output:
Object a is iterable
Object b is not iterable
23.Sorting a List of Tuples
You can sort a list of tuples using the itemgetter() function of
the operator module. The itemgetter is passed as a key to the
sorted() function. If you want to sort by the first name, you pass
the index (0) to the itemgetter function. Below are different
ways you can use the itemgetter to sort the list of tuples.
from operator import itemgetter
names = [('Ben','Jones'),('Peter','Parker'),
('Kelly','Isa')]
To sort the list in ascending order, we can just change the index
to [:]. See below:
list1 = ['Mary','Peter', 'Kelly']
a = lambda x: x[:1]
y = sorted(list1, key=a)
print(y)
Output:
['Kelly', 'Mary', 'Peter']
Below we access the title of the article. You can also access the
article's text.
from newspaper import Article
news = Article("https://indianexpress.com/article/"
"technology/gadgets/"
"apple-discontinues-its-last-ipod-model-7910720/")
news.download()
news.parse()
print(news.title)
Output
End of an Era: Apple discontinues its last iPod model
26.A List of Tuples with Enumerate
Since enumerate counts (adds a counter) the items it loops over,
you can use it to create a list of tuples. Below we create a list of
tuples of days in a week, from a list of days in a week. Enumerate
has a parameter called start. Start is the index you want the
count to begin. By default, the start is zero(0). Below, we have
set start at one(1). You can put any number you want as start.
days = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"]
Tuples properties
1. They are surrounded by round brackets ( ).
2. They are ordered
3. They are immutable
4. They can hold arbitray objects.
27.Windows Warning Sound
Did you know that if you run print(‘\a’) your windows machine
will make a warning sound? Try this code below:
import time
for i in range(5):
for j in range(4):
for k in range(3):
time.sleep(0.3)
print('\a')
print('\a')
time.sleep(1)
28.Print Colored Texts
Did you know that you can add color to your code using Python
ansi escape codes: Below, I created a class of codes and I apply
it to the code that I print out.
class Colors():
Black = '\033[30m'
Green = '\033[32m'
Blue = '\033[34m'
Magenta = '\033[35m'
Red = '\033[31m'
Cyan = '\033[36m'
White = '\033[37m'
Yellow = '\033[33m'
str1 = 'string'
for i, j in enumerate(str1):
if j =='n':
print(f"The index of n is {i}")
Output
The index of 'n' is 4
30.A Class Using the Type Function
The type() function is usually used to check the type of an object.
However, it can also be used to create classes dynamically in
Python. Below I have created two classes, the first one using the
class keyword and the second one using the type() function. You
can see that both methods achieve the same results.
# Creating dynamic class using the class keyword
class Car:
def __init__(self, name, color):
self.name = name
self.color = color
def print_car(self):
return f'The car is {self.name} ' \
f'and its {self.color} in color'
str1 = ''
if not str1:
print('This string is empty')
else:
print('This string is NOT empty')
Output:
This string is empty
Example 2
str2 = 'string'
if not str1:
print('This string is empty')
else:
print('This string is NOT empty')
Output:
This string is NOT empty
32.Nested List and the Sum Function
You can flatten a nested list using the sum() function. Note that
this will work on a two-dimensional nested list.
new_list = sum(nested_list,[])
print(new_list)
Output:
[2, 4, 6, 8, 10, 12]
Please note that this is not the mos efficient way to flatten a list.
But its freaking cool to know it , right? 😊
file = os.path.exists('file.txt')
if file:
print('This file exist')
else:
print('This file does Not exist')
Output:
This file does Not exist
34.Set Comprehension
Set comprehension is similar to list comprehension; the only
difference is that it returns a set and not a list. You can use set
comprehension on an iterable (list, tuples, set, etc).
Let’s say you have a list of uppercase strings and you want to
convert them into lowercase strings and remove duplicates; here
is how you do it using set comprehension. Since sets are not
ordered, the order of the items in the iterable will be changed. Sets
do not allow duplicates, so only one ‘PEACE’ will be in the output
set.
list1 = ['LOVE', 'HATE', 'WAR', 'PEACE', 'PEACE']
set1 = {word.lower()for word in list1}
print(set1)
Output:
{'love', 'peace', 'war', 'hate'}
Set properties
1. Sets are not ordered.
2. They are surrounded by curly brackets
3. Sets are mutable
4. Sets do not allow duplicates.
5. They can only hold immutable type objects. For example,
you cannot put a list inside a set; it will generate an error.
See below:
a = {[2,4]}
print(a)
Output:
TypeError: unhashable type: 'list'
35.Python *args and **Kwargs
When you are not sure how many arguments you will need for your
function, you can pass *args(Non Keywords Arguments) as a
parameter. The * notation tells Python that you are not sure how
many arguments you need and Python allows you to pass in as
many arguments as you want. Below, we calculate average with
different number of arguments
def avg(*args):
avg1 = sum(args)/len(args)
return f'The average is {avg1:.2f}'
Dictionary properties
1. Dictionaries are surrounded by curly brackets
2. Dictionaries cannot have duplicate keys, but can have
duplicate values
3. Dictionaries keys must be immutable
4. Dictionaries are now ordered(since Python 3.7). They
remember the order of items inserted.
38.DataFrame from Two Lists
The easiest way to create a DataFrame from two lists is to use the
pandas module. Import pandas module and pass the lists to the
DataFrame constructor. Since we have two lists, we have to use the
zip() function to combine the lists.
Below, we have a list of car brands and a list of car models. We are
going to create a DataFrame. The DataFrame will have one column
called Brands, and another called Models, and the index will
be the numbers in ascending order.
list1 = ['Tesla', 'Ford', 'Fiat']
models = ['X', 'Focus', 'Doblo']
df = pd.DataFrame(list(zip(list1,models)),
index =[1, 2, 3],
columns=['Brands','Models'])
print(df)
Output:
Brands Models
1 Tesla X
2 Ford Focus
3 Fiat Doblo
39.Adding a Column to a DataFrame
Let’s continue with the tip from the previous question. Let’s add a
column called Age to the DataFrame. The column will have the
ages of the cars.
import pandas as pd
df = pd.DataFrame(list(zip(list1,models)),
index =[1, 2, 3],
columns=['Brands','Models'])
print(df)
Output:
Brands Models Age
1 Tesla X 2
2 Ford Focus 4
3 Fiat Doblo 3
40.Code Timer as a Decorator
Below I created a timer function using the perf_counter class of
the time module. Notice that the inner function is inside the
timer function; this is because we are creating a decorator. This
decorator is later used by the range_tracker function. The
@timer right before the function means that the function is
being decorated by another function. To decorate a function
is to improve or add extra functionality to that function
without modifying it. By using a decorator, we are able to add
a timer to the range_tracker function. We are using this timer to
check how long it takes to create a list from a range.
import time
def timer(func):
def inner():
start = time.perf_counter()
func()
end = time.perf_counter()
print(f'Run time is {end-start:.2f} secs')
return inner
@timer
def range_tracker():
lst = []
for i in range(10000000):
lst.append(i**2)
range_tracker()
Output:
Run time is 10.25 secs
41.List Comprehension vs Generators
A generator is similar to a list comprehension, but instead of
square brackets, you use parenthesis. Generators yield one item
at a time, while list comprehension releases everything at a time.
Below, I compare list comprehension to a generator in two
categories:
1. Speed of execution.
2. Memory allocation.
Conclusion.
List comprehension executes much faster but takes up more
memory. Generators execute a bit slower, but they take up less
memory since they only yield one item at a time.
import timeit
import sys
def timer(_, code):
exc_time = timeit.timeit(code, number=1000)
return f'{_}: execution time is {exc_time:.2f}'
def memory_size(_, code):
size = sys.getsizeof(code)
return f'{_}: allocated memory is {size}'
one = 'Generator'
two = 'list comprehension'
print(timer(one, 'sum(num**2 for num in range(10000))'))
print(timer(two, 'sum([num**2 for num in range(10000)])'))
print(memory_size(one,(num**2 for num in range(10000))))
print(memory_size(two,[num**2 for num in range(10000)]))
Output:
Generator: execution time is 5.06
list comprehension: execution time is 4.60
Generator: allocated memory is 112
list comprehension: allocated memory is 85176
42.Writing to File
Let’s say you have a list of names and you want to write them
to a file and you want all the names to be written vertically.
Here is a sample code that demonstrates how you can do it.
The code below creates a CSV file. We use the escape character
(‘\n’) to tell the code to write each name in a new line. Another
way you can create a CSV file is by using the CSV module.
import PyPDF2
from PyPDF2 import PdfFileMerger,
PdfFileReader,PdfFileWriter
list1 = ['file1.pdf', 'file2.pdf']
merge = PyPDF2.PdfFileMerger(strict=True)
for file in list1:
merge.append(PdfFileReader(file,'rb+'))
merge.write('mergedfile.pdf')
merge.close()
created_file = PdfFileReader('mergedfile.pdf')
created_file
Output:
<PyPDF2.pdf.PdfFileReader at 0x257d1c8ba90>
44.Return vs Yield
The difference between the return statement and the yield
statement.
The return statement returns one element and ends the function.
The yield statement returns a 'package' of elements called a
generator. You have to ‘unpack’ the package to get the elements.
You can use a for loop or the next() function to un-pack the
generator.
print(num(5))
Output:
0
Example 2 : Using yield
def num (n: int):
for i in range(n):
yield i
# creating a generator
gen = num(5)
#unpacking generator
for i in gen:
print(i, end = ' ')
Output:
01234
45.High Order Functions
A high order function is a function that takes another function
as an argument, or returns another function. The code below
demonstrates how we can create a function and use it inside a
high order function. We create a function called sort_names
and we use it as a key inside the sorted() function. By using
index[0] we are basically telling the sorted function to sort
names by their first name. If we use [1], then the names would
be sorted by the last name.
def sort_names(x):
return x[0]
names = [('John','Kelly'),('Chris','Rock'),
('Will','Smith')]
!pip3 install -
U git+https://github.com/PrithivirajDamodaran/G
ramformer.git
print(this)
Output:
The Zen of Python, by Tim Peters
Please note that Pprint does not change the order of the actual
dictionary; it just changes the printout order.
49.Convert Picture to grey Scale
Do you want to convert a color image into grayscale? Use
Python’s cv2 module.
First install cv2 using > pip install opencv-python<
Below we are converting a color book image to grayscale. You
can replace that with your own image. You must know where
the image is stored.
When you want to view an image using CV2 a window will open.
The wait key() in milliseconds, is the time you want the window
to stay open before it closes.
import cv2 as cv
img = cv.imread('book.jpg')
#Save image
cv.imwrite('grayed.jpg', grayed_img)
50.Time it with timeit
If you want to know the execution time of a given code, you can
use the timeit() method. Below, we create a timer function, with
the timeit function. The timeit function takes the code we want
to check and the number of executions we want to
run(number=1000). When we call the function, We then pass a
code to the function to determine execution time. Basically,
below we are using timeit to check how long it takes to execute
sum(num**2 for num in range(10000)).
import timeit
def timer(code):
tm = timeit.timeit(code,number=1000)
return f'Execution time is {tm:.2f} secs.'
if __name__ == "__main__":
print(timer('sum(num**2 for num in range(10000))'))
Output:
Execution time is 5.05 secs.