- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are the best practices for using loops in Python?
This is a language agnostic question. Loops are there in almost every language and the same principles apply everywhere. You need to realize that compilers do most heavy lifting when it comes to loop optimization, but you as a programmer also need to keep your loops optimized.
It is important to realize that everything you put in a loop gets executed for every loop iteration. The key to optimizing loops is to minimize what they do. Even operations that appear to be very fast will take a long time if the repeated many times. Executing an operation that takes 1 microsecond a million times will take 1 second to complete.
Don't execute things like len(list) inside a loop or even in its starting condition.
example
a = [i for i in range(1000000)] length = len(a) for i in a: print(i - length)
is much much faster than
a = [i for i in range(1000000)] for i in a: print(i - len(a))
You can also use techniques like Loop Unrolling(https://en.wikipedia.org/wiki/Loop_unrolling) which is loop transformation technique that attempts to optimize a program's execution speed at the expense of its binary size, which is an approach known as space-time tradeoff.
Using functions like map, filter, etc. instead of explicit for loops can also provide some performance improvements.
- Related Articles
- What are the best practices for using if statements in Python?
- What are the “best practices” for using import in a Python module?
- What are the best practices for exception handling in Python?
- What are the best practices for committing in Git?
- What are Python coding standards/best practices?
- What are the best practices for function overloading in JavaScript?
- What are the best practices to organize Python modules?
- Best practices for using MySQL indexes?
- What are the best practices to be followed while using JavaScript?
- What are the best practices to keep in mind while using packages in Java?
- Best practices for Java comments.
- What are common practices for modifying Python modules?
- Best practices for writing a Dockerfile
- What are the best practices to improve jQuery selector performance?
- What are the Best Practices to Improve CRM User Adoption?
