Top basic Python hacks all programmers must know

Python emerged as the top programming language in the TIOBE index in 2021. The exponential rise of the data science ecosystem in general and the popularity of Python libraries like Pandas, Tensorflow, PyTorch, and NumPy for AI/ML workflows powered the growth of Python. However, while Python is the go-to for many, most are still unaware of the basic Python hacks that can make the programming process easier and faster. This article discusses the top Python hacks all programmers must know.

Trimming

The trimming hack is useful for scraping unwanted data. It helps users trim unwanted text or special characters in a string. This includes special characters like newlines, tabs or unwanted text like t, n, t, etc. The code snippet below can tackle the garbage strings in web data extraction. The hack in Python named strip () will trim all the scraped data.

data = ” n n nPython n n t”

print (data.strip (“ n t”)) # Python

data = “ n nCoding”

print (data.strip ()) # Coding

Merging two dictionaries

This Python hack helps the user merge two dictionaries of any length into one. Check out the below code example. The most commonly used trick is the ** (double star). The single expression is used to merge two dictionaries and store it in a third dictionary. The double star implies an argument is a dictionary and works as a shortcut to pass multiple arguments to a function directly using a dictionary.

Example code:

# expression

def Merge (dict1, dict2):

res = {** dict1, ** dict2}

return res

# Driver code

dict1 = {‘a’: 10, ‘b’: 8}

dict2 = {‘d’: 6, ‘c’: 4}

dict3 = Merge (dict1, dict2)

print (dict3)

Output: ‘x’: 10, ‘a’: 6, ‘b’: 4, ‘y’: 8}

Transferring a list to string

In Python, a list is an ordered sequence holding a variety of object types like an integer, character or float while a string is an ordered sequence of characters. Convering a list into a string is a common Python function. While the Loop approach is prevalent, this hack is easier.

# Iterable to List

mylist1 = [“Eat”, “Sleep”, “and”, “Code”]

print (”“ .join (mylist1)) # Eat Sleep and Code

mylist2 = [“Learn”, “Programming”, “From”, “Scratch”]

print (”“ .join (mylist2)) # Learn Programming From Scratch

Calculate execution time

Python modules like time, timeit, and DateTime store the time-stamps when a particular program section is executed. These can be manipulated to calculate the time taken to execute the program. The timeit module works only with small code snippets, and the rest can take a long time. This hack provides the easiest way to calculate the time.

import time

start_time = time.time ()

func ()

end_time = time.time ()

print (“Execution Time:“, (end_time-start_time))

Shorten names

Python has umpteen libraries across languages. Creators always find it difficult to deal with the libraries while developing a program, especially given bigger and regional names. The ‘as’ keyword allows developers to shorten the library’s name.

## Normal Way

import NumPy

import speech_recognition

## Shorten Name

import NumPy as np

import speech_recognition as sr

Comparing two unordered lists

This hack comes in handy when users have two lists with the same elements but are structured in different orders.

From collections import Counter

a = [1, 2, 3, 1, 2, 3]

b = [3, 2, 1, 3, 2, 1]

print (Counter (a) == Counter (b))

Sorting lists

Python has two main functions, sorted () and sort (), for sorting collections. They can sort between lists, tuples, and dictionaries.

When it comes to sorting a list, the desired outcome is changing the original without needing a new variable. Using the sorted () function often creates a new list. The easiest way to do this is by using sort (), which sorts the list in its original place.

For example:

list_1 = [24, 54, -1, 4, 0, 76]

print (‘Before Sorting:’, list_1) list_1.sort ()

print (‘After Sorting:’, list_1)

Output:

Before Sorting: [24, 54, -1, 4, 0, 76]

After Sorting: [-1, 0, 4, 24, 54, 76]

Converting two lists into a dictionary

Real-time applications in Python usually require interconversion between data types. This is true, especially when users deal with two lists in different formats: keys and values. Often, certain systems have certain modules requiring the input to be in a particular data type. There are two key hacks to converting two lists into a dictionary for such purposes.

  1. Using the zip () method

The zip () is the easiest method that pairs the list element with another list element at the corresponding index in the form of key-value pair.

# using zip ()

# to convert lists to dictionary

res = dict (zip (test_keys, test_values))

  1. The dictionary comprehension method

The dictionary comprehension method is a faster and concise method to convert lists since it reduces the lines.

# using dictionary comprehension

# to convert lists to dictionary

res = {test_keys[i]: test_values[i] for i in range (len (test_keys))}

Leveraging sets

Sets is one of 4 built-in data types in Python, along with List, Tuple, and Dictionary, to store data collections. It stores multiple items in a single variable. Though sets are unordered, unchangeable, and unindexed, they offer high performance. If the program does not require a lot of functionality, sets can be the go-to option.

Itertools in Python

Itertools module provides various functions that work on iterators to generate complex iterators. It standardises a core set of fast and memory-efficient tools useful by themselves or in combination. They form an “iterator algebra” to construct specialized tools succinctly and efficiently in pure Python to handle iterators. Here, for instance, itertools.combinations () can be used for building combinations. The input values ​​can be grouped in other combinations as well.

Leave a Comment