10 Coolest Python Features — Part I

Hidden Python features that you may not know

Photo by Chris Ried on Unsplash

1. For Else

We all knew about the if-else in programming. Python offers a different feature to have else condition if for-loop.

Using 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.

Using yield keyword

3. Pprint

Python is also widely used for Web Development. Frameworks like Django and Flask are quite famous for web development in Python.

Using print
Using pprint
print and pprint code

4. Comparison Chaining

Comparison Channing offers a way to link multiple comparison statements without using and keyword.

Comparison Chaining

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.

timeit

Thank you 🤘

To know more about me, visit ganeshkumarm.me

SDE II at Amazon. ✍️ Blog Writer 🔸 👨‍💻 Full Stack Engineer