The array is a vector containing homogeneous elements, i.e same data types. All the elements are saved in continuous memory location so it has a better performance to lists in python. One important thing here we have to remember is that while creating an array we have to import the
array built-in module and predefine the data type which we want to use.
import array arr = array.array('i', [10, 20, 30])
A list is a collection of items containing heterogeneous elements, i.e different data types, which may be either int, float, string, etc. It is not necessary that all elements of an array would be stored in a contiguous memory location.
lst = [1, 'two', 3.0]
Until a few days back I always thought arrays to be the same as the list in python, though I have been working professionally with Python for more than 5 years now. Array data type in python is something which many of you might never have heard of and in all probabilities, you might almost never use it, but then why do we need to know about this? The answer is simple you need to know this for interviews 😜. But apart from this reason, you might have other use cases like
arrayin python is a thin wrapper on top of the
Carray, it provides a space efficiency when it comes to storage.
- When you have a known set of values to be used, then using an array would give you a performance boost as arrays are stores continuously in the memory address to it would have faster access of elements and also would consume lesser memory.
numpyand few other libraries use python
arrayunder the hood to build their efficient array datatype.
You can read more about the syntax and how to use python in the official documentation