Array and List
Table of contents:
Array and List
As learning Python, people usually get confused between Array
and List
. List
is a python built-in method and the Array
is built in NumPy. Both are the methods that are commonly used in Python in order to store data. It can store any datatype such as numbers, string, etc. They can both be indexed and iterated. However, they do not serve the same purposes. The main difference is that the Array
has the Array Broadcasting functionality in NumPy but List
does not have.
Array Broadcasting
Broadcasting is simply a set of rules for applying binary ufuncs (e.g., addition, subtraction, multiplication, etc.) on arrays of different sizes. Broadcasting in NumPy follows a strict set of rules to determine the interaction between the two arrays:
- If the two arrays differ in their number of dimensions, the shape of the one with fewer dimensions is padded with ones on its leading (left) side.
- If the shape of the two arrays does not match in any dimension, the array with shape equal to 1 in that dimension is stretched to match the other shape.
- If in any dimension the sizes disagree and neither is equal to 1, an error is raised.
Scalar and One-Dimensional Array
array([5, 6, 7])
array([5, 6, 7])
One-Dimensional Array and Two-Dimensional Array
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
array([[1., 2., 3.],
[1., 2., 3.],
[1., 2., 3.]])
More Complicated Cases in Broadcasting of Both Arrays
[0 1 2]
[[0]
[1]
[2]]
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
Array Broadcasting Functionality on List and Array
Now, we have some basic understanding on the Array Broadcasting functionality. Let’s setup a 2-d array, 1-d array and a list to do the experiment.
array([[0.58758076, 0.74464029, 0.68320516],
[0.98230461, 0.24750985, 0.05020555]])
array([1, 2, 3, 4])
[1, 2, 3, 4]
array([[1.17516152, 1.48928058, 1.36641033],
[1.96460922, 0.49501969, 0.1004111 ]])
array([2, 4, 6, 8])
[1, 2, 3, 4, 1, 2, 3, 4]
The broadcasting functionality works fine on arrays but not on the list. The list was repeated with the multiplication operation.
array([[0.29379038, 0.37232015, 0.34160258],
[0.4911523 , 0.12375492, 0.02510277]])
rray([0.5, 1. , 1.5, 2. ])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-15-388b6a901f4d> in <module>
1 # Division operation on the list
2 alist = [1, 2, 3, 4]
----> 3 alist/2
TypeError: unsupported operand type(s) for /: 'list' and 'int'
The result above shows that the broadcasting functionality cannot be applied on the list. Thus, we can see the main different between Array
and List
.
Reference: