Python NumPy - Numerical Operations on Arrays
Premium
Arrays have a unique advantage over Python lists in that they allow you to perform element-wise operations without the need for a for loop. This makes computations very efficient specially while dealing with large data sets.
Suppose we have a list and we want to multiply all its elements by 3 (scalar). If we try to directly multiply it by three, it will just add the list elements three times, which is not what we wanted.
1>>> a = [1,3,5]
2>>> a*3
3[1, 3, 5, 1, 3, 5, 1, 3, 5]
4>>>
5
To get the right results, you will use the for-loop approach which would look as follows:
1>>> a = [1,3,5]
2>>> b = [3*x for x in a]
3>>> b
4[3, 9, 15]
5>>>
6
Unlock Premium Content
Upgrade your account to access the full article, downloads, and exercises.
You'll get access to:
- Access complete tutorials and examples
- Download source code and resources
- Follow along with practical exercises
- Get in-depth explanations