Some days back, I was working on a Python project and I had to make use of lists. I created an empty list and named itcost_array. A friend saw this and asked the question:
?What is the difference between a List and an Array??
- Both are used for storing data
- Both are mutable
- Both can be indexed and iterated through
- Both can be sliced
The main difference between these two data types is the operation you can perform on them. Arrays are specially optimised for arithmetic computations so if you?re going to perform similar operations you should consider using an array instead of a list.
Also lists are containers for elements having differing data types but arrays are used as containers for elements of the same data type.
The example below is the result of dividing an array by a certain number and doing the same for a list. When we try the same operation (example: division) on a list, we get a TypeError because builtin python lists do not support the `__div__` protocol. It takes an extra step to perform this calculation on a list because then you?d have to loop over each item one after the other and save to another list.
Making use of more robust array data types isn?t also without it?s cost implications. For example, to use numpy arrays you need to introduce a dependency in your project on the numpy library. You?d have to install the numpy package, import it and declare it while a list can be created on the fly.
While numpy provides a more robust array data type suited for numerical computation, Python also has a builtin array data type.
Before you go?
Thanks for reading!
If you enjoyed this article, please hold down the clap button ? to help others find it. The longer you hold it, the more claps you give!
And do not hesitate to share your thoughts in the comments below.