7 Amazing Basic Python Hacks You Should Know 2022!

plabs.id
4 min readFeb 9, 2022

Python is indeed one of the smartest and most trending languages. It is simple to learn and implement, yet very effective for complex machine learning tasks. And the fact that there are tons of Python libraries to help us do the task quickly.

In this article, we have created 7 Python hacks that are sure to save you a lot of time, effort and make you more effective in your work. Here are some cool hacks that make python superb among all other languages.

1. Use .join instead of + to perform string concatenation

Don’t

Do

Example:

Input

Output

2. Use zip to iterate over multiple lists

Don’t

Do

Output

Example:

Input

Output

3. For loops use List comprehension for readable

Lists in Python are similar to arrays. It is mutable, can store heterogeneous elements, and is easy to use. Now to add elements to the array, you need to run the loop and then add the elements one by one. Also If there are requirements involved then the code size increases. Python provides a more efficient way to do this by combining all the steps in one line called List comprehension.

Don’t

Do

4. Use sets a little more than you already do

Sets offer performance over functionality. If you don’t need a lot of functionality in your current situation, prefer pools over other data structures.

Output

5. Printing the repeated character

The task is to print the pattern like this Plabsssss. So we can easily print this pattern without using it for a loop.

Output

6. Collection in Python

Collection in python are containers that are used to store the collection of data. Python provides a package collection that contains different types of useful containers that can be used for different purposes.

For Example:

Counter — Takes an iterable and returns a dictionary where Keys = elements and Value = their count in the iterable.

Namedtuple — Returns a tuple with names for each position in the tuple.

Ordered Dict — Type of dictionary where the order is maintained at any cost.

Default Dict — Contains default values for each key if not assigned.

Count occurrence of elements

It is good to have an idea of the number of times elements occurred in your data structure.

Output

7. Pretty Print data structure (pprint)

pprint is a built-in module in Python. It gives you the ability to print arbitrary data structures in a ‘pretty’ format that is well-formatted and much more readable.

Input

Don’t

Output

But… What you have to do is…

Do

Output

That’s about some basic ways you can improve your script with python. Follow the style guide and be a gracious programmer!!

Sources:

https://towardsdatascience.com/10-quick-and-clean-coding-hacks-in-python-1ccb16aa571b

https://www.analyticsvidhya.com/blog/2020/04/7-python-hacks-tips-tricks-data-science/

--

--

PLABS.ID is a technology company based in Indonesia since 2019, we're on a mission to simplify digitalization at every touchpoint.