Python Tricks and Tips that You Should Know.

Benjamin Bennett Alexander
3 min readMar 21, 2022
Photo by Pavel Danilyuk from Pexels

When you start learning Python, it may take a while to pick up some tips and tricks that will make your programming life much easier. In this article, we are going to explore some tricks and tips that you can use in your code.

1. Printing horizontally

When looping through an iterable, the print function prints each item in the new line. This is because the print function has a parameter called end. By default, the end parameter has an escape character (end =’\n’). To print horizontally, we need to remove the escape character and replace it with an empty string (end = “ “). Here is the code to demonstrate that:

2. Merging dictionaries

If you have two dictionaries that you want to combine, you can combine them using two easy methods. You can use the merge (|) operator or the (**) operator. Below, we have two dictionaries, a and b. We are going to use these two methods to combine the dictionaries. Here is the code below:

3. Flatten a nested list

If you have a nested list( [[1, 2,3],[4, 5,6]]) and you want to flatten it, you can use the chain class from the itertools module. See the code below:

4. Count occurrences of an item in a list

If you have a list of items and you want to know how many times each item appears in the list, you can use the counter class from the collections module. Let’s say we want to know how many times the name ‘Peter’ appears in the list; here is how we can do it using the counter class.

5 . Print Pretty

Let’s say you have a dictionary and you want to print out the elements sorted alphabetically; you can use the pprint module. Here is the code to demonstrate that:

Conclusion

There you have it, tips and tricks that you may use in your code. If you know other Python tips and tricks, please share them in the comment section below. Thanks for reading and get my book below if you are interested in taking your Python skills to another level.

--

--

Benjamin Bennett Alexander

Tech ( Python, Data science and Blockchain) and Finance enthusiast. I just share stories.