- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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.
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.
- What are the best practices for using if statements in Python?
- 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 to organize Python modules?
- Best practices for using MySQL indexes?
- What are best practices to define Python classes?
- Best practices for Java comments.
- What are common practices for modifying Python modules?
- What are the best practices to improve jQuery selector performance?
- Best practices for writing a Dockerfile
- What are the best practices to keep in mind while using packages in Java?
- What are favicon best practices regarding size and format?