10 Coolest Python Features — Part I

Hidden Python features that you may not know

Photo by Chris Ried on Unsplash

Python is one of the easiest languages to learn. I got attracted by Python during my college because of its simplicity and ease of learning. Though it is simple to learn, it is one of the powerful languages too. It is quite famous for complex tasks like Machine Learning, Image Processing, NLP, etc.

In this article, we will be looking into the 10 hidden and coolest features of python which many people (I was one of them 😉) may not have heard of.

1. For Else

Consider an example where you are given an array and you have to print Yes if all the elements in the array are even else print No.

The traditional way to solve this problem is to use a flag variable and print Yes or No based on that.

Using a flag variable

We can solve the same problem without a flag variable using for-else

Using for-else

2. Yield

Method 1

Method 2

We can solve this efficiently with the python yield keyword.

Using yield keyword

Instead of a return in the method, we need to add the yield keyword. This makes the above function a Generator. A Generator does not store all values in memory, instead, it gives the next value when it is called by the next method.

3. Pprint

When web development comes into the picture, we can’t ignore JSON that easily. We deal with JSON data and we also need to print it for debugging. Printing JSON using the print statement is one of the worst things to do.

Let us print the JSON data from the API https://api.github.com/users/ganeshkumarm1 using Python print.

Using print

See, how ugly it is. Now we print the same data with pprint.

Looks awesome. Right?

Using pprint
print and pprint code

4. Comparison Chaining

Comparison Chaining

5. Timeit

timeit

Please do read the Part II of this article here.

Thank you 🤘