10 Coolest Python Features — Part I
Hidden Python features that you may not know
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
We all knew about the if-else in programming. Python offers a different feature to have else condition if for-loop.
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.
We can solve the same problem without a flag variable using for-else
2. Yield
Consider an example where we want to generate a sequence of numbers (up to 100 Million) in our program (like auto-incremented ids). We can solve this problem easily with the below methods.
Method 1
We can generate all the ids and store them in a list. But, keeping all the 100M values in memory will not be efficient.
Method 2
We can have a global variable and increment the value each time when the generate_ids method is called. But, in general keeping global variables in a program is not recommended.
We can solve this efficiently with the python 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
Python is also widely used for Web Development. Frameworks like Django and Flask are quite famous for web development in Python.
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.
See, how ugly it is. Now we print the same data with pprint.
Looks awesome. Right?
4. Comparison Chaining
Comparison Channing offers a way to link multiple comparison statements without using and keyword.
5. Timeit
Python provides a simple way to calculate the runtime of our code using timeit. Instead of calculating the difference between the start time and end time of our code once, timeit executes the code N number of times and gives a better value for the runtime. By default, the code is executed 1 Million times.
Please do read the Part II of this article here.
Thank you 🤘
To know more about me, visit ganeshkumarm.me