{"id":366,"date":"2022-09-27T00:00:00","date_gmt":"2022-09-27T00:00:00","guid":{"rendered":"https:\/\/tac.debuzzify.com\/?p=366"},"modified":"2023-06-27T05:23:21","modified_gmt":"2023-06-27T05:23:21","slug":"speed-up-slow-for-loops-in-python","status":"publish","type":"post","link":"https:\/\/www.the-analytics.club\/speed-up-slow-for-loops-in-python\/","title":{"rendered":"Is Your Python For-loop Slow? Use NumPy Instead"},"content":{"rendered":"\n\n\n
Speed is always a concern for developers \u2014 especially for data-savvy work.<\/p>\n\n\n\n
The ability to iterate is the basis of all automation and scaling. The first and foremost choice for all of us is a for-loop. It\u2019s excellent, simple, and flexible. Yet, they are not built for scaling up to massive datasets.<\/p>\n\n\n\n
This is where vectorization comes in. When you do extensive data processing in for-loops, consider vectorization. And Numpy comes in handy there.<\/p>\n\n\n\n
This post explains how fast NumPy operations are compared to for-loops.<\/p>\n\n\n\n
Grab your aromatic coffee <\/a>(or tea<\/a>) and get ready…!<\/p>\n<\/div>\n<\/div>\n<\/div>\n\n\n\n Let\u2019s take a simple summation operation. We have to sum up all the elements in a list.<\/p>\n\n\n\n The sum is an inbuilt operation in Python<\/a> you can use over a list of numbers. But let\u2019s assume there isn\u2019t one, and you need to implement it.<\/p>\n\n\n\n Any programmer would opt to iterate over the list and add the numbers to a variable. But experienced developers know<\/a> the limitations and go for an optimized version.<\/p>\n\n\n\n Here are both the list and NumPy versions of our summation. We create an array with a million random numbers between 0 and 100. Then we use both methods and record the execution times.<\/p>\n\n\n\n Comparing For-loops with NumPy<\/h2>\n\n\n\n