The Best Basic Python Hacks Every Programmer Should Know

0

Python became the top programming language in the TIOBE index in 2021. The exponential growth of the data science ecosystem in general and the popularity of Python libraries such as Pandas, Tensorflow, PyTorch and NumPy for workflows AI/ML fueled the growth of Python. However, although Python is the go-to for many, most still ignore basic Python hacks that can make the programming process easier and faster. This article discusses the best Python hacks that every programmer should know.

Garnish

The slicing hack is useful for deleting unwanted data. It helps users to cut off 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 unnecessary strings in web data extraction. The Python hack named strip() will remove all retrieved data.

data = “nnnPythonnnt”

print(data.strip(“nt”)) # Python

data = “n nCoding”

print(data.strip()) # Coding

Merge two dictionaries

This Python hack helps user to merge two dictionaries of any length into one. See the sample code below. 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 that an argument is a dictionary and works as a shortcut for passing multiple arguments to a function directly using a dictionary.

Example code:

# expression

def Merge(dict1, dict2):

res = {**dict1, **dict2}

back 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}

Transfer from a list to a channel

In Python, a list is an ordered sequence containing a variety of object types like an integer, a character, or a float, while a string is an ordered sequence of characters. Converting a list to a string is a common Python function. Although the Loop approach is widespread, this hack is easier.

# Iterable to list

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

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

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

print(” “.join(mylist2)) # Learn programming from scratch

Calculate execution time

Python modules such as time, timeit, and DateTime store timestamps when a particular program section is executed. These can be manipulated to calculate the time it takes for the program to run. The timeit module only works with small code snippets, and the rest can take a long time. This hack provides the easiest way to calculate time.

import time

start_time = time.time()

function()

end_time = time.time()

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

Shorten names

Python has countless libraries in all languages. Creators always find it difficult to deal with libraries when developing a program, especially given the larger and regional names. The ‘as’ keyword allows developers to shorten the library name.

## Normal route

import NumPy

import voice recognition

## Shorten name

import NumPy as np

import voice recognition as sr

Compare two unordered lists

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

From the collection import counter

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

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

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

Sort 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 result is to change the original without needing a new variable. Using the sorted() function often creates a new list. The easiest way to do this is to use 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)

Production:

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 generally require interconversion between data types. This is especially true when users are dealing with two lists in different formats: keys and values. Often some systems have certain modules requiring the input to be in a particular data type. There are two key hacks to convert two lists into a dictionary for these purposes.

  1. Using the zip() method

The zip() is the simplest method that associates the list item with another list item at the corresponding index as a 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 more concise way to convert lists because it reduces lines.

# using dictionary comprehension

# to convert lists to dictionary

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

Take advantage of sets

Sets is one of the 4 built-in data types in Python, along with List, tupleand Dictionary, to store collections of data. It stores multiple items in a single variable. Although sets are unordered, unmodifiable, and unindexed, they provide high performance. If the program doesn’t require a lot of features, bundles might be the option of choice.

Itertools in Python

The Itertools module provides various functions that work on iterators to generate complex iterators. It standardizes a basic set of fast, memory-efficient tools that can be used alone or in combination. They form an “algebra of iterators” to construct specialized tools in a succinct and efficient way in pure Python to manage iterators. Here, for example, itertools.combinations() can be used to create combinations. Input values ​​can also be grouped in other combinations.

Share.

Comments are closed.