Arsalan Ali's profile picture
Arsalan Ali
@arslanchaos
View on Twitter

Ever wondered what algorithm can sum a list/array the fastest in Python? Here's a surface level overview

A Thread ๐Ÿงต๐Ÿ‘‡

#python3 #pythonic #pythonprogramming #programming #Algorithms #DataScience

First of we generated a random list of "1000000" numbers to feed all the algorithms.

This very first algorithm uses the built-in sum method. Its the easiest one to implement.

Second algorithm is just the traditional approach of creating a variable and then using a for loop to add the sum into it.

Third algorithm isn't basically anything new. As a matter of fact its written to slow down the process because sum method already iterates on a list/array. So giving it a for loop should slow it down. It's just for experimental purposes.

Fourth algorithm is based on reduce method. You need to specify some sort of function in it. You can use it without defining a function but for the sake of consistency we've written it like this.

Lastly we've used the Numpy Sum method in the fifth algorithm.

As you can see from the results, Numpy Sum is the winner here. It beats the built-in Sum method by quite a margin. Meanwhile our Sum Loop approach performs the worst as expected. Reduce and Loop algorithms are almost similar in performance.

Hope you liked the surface-level review and it helped you to choose the better algorithm for your project next time. ๐Ÿ˜Š๐Ÿฅณ

If you want more content like this, make sure to follow me.

Help us raise more money for charities by sharing this content โ™ฅ๏ธ
Wait! Before you go...
Grab Exclusive Deals for Books, Courses, Software.
100% of Profits Are Donated To Research-Backed Charities.