# What are some common operations that can be applied to NumPy Arrays?

### Question

What are some common operations that can be applied to NumPy Arrays?

Most operations that you can apply on two numerical values in Python can also be applied to NumPy Arrays.

Common operations that are element-wise include addition, subtraction, multiplication, division, modulo and exponent.

#### Example of some operations

``````example = np.array([12, 34, 45, 67, 89])

example + 1
# [13, 35, 46, 68, 90]

example * 10
# [120, 340, 450, 670, 890]

example % 10
# [2, 4, 5, 7, 9]
``````
2 Likes

I don’t see why numpy arrays are used instead of lists, if we carry out the below function it seems like it can just as easily be done through a comprehension :

``````a = [1.0, 2.0, 3.0]
doubled = [x *2 for x in a]
``````
2 Likes

I believe the reason is for all of the other operations that can be performed such as adding, multiplication and other math functions that can be performed directly on numPy arrays.

Ah I see. So do you think lists are redundant then and i should avoid using them and instead use numpy arrays in all situations?

No, lists are not redundant. Remember lists can hold any type of data (strings, class instances, Boolean, ect), and numpy arrays are mainly focused on numeric proccesing. It all depends on what you are using it for.
And remember you can get this functionality out of a list but you would have to write all the functions to do the calculations on lists. It could be done but NumPy has made it easier.
Hope this helps.

4 Likes

a = np.array(l)
What is the function of “l” in the bracket?

Where are you pulling this variable from?

a = np.array(l)

Normally you would put `a = np.array([ 1, 2, 3 ])` to create an numpy array.

Hey,
I copied it from " Introduction to NumPy" exercise 5

# With an array

a = np.array(l)
a_plus_3 = a + 3

FROM THE LESSON

``````# With a list
l = [1, 2, 3, 4, 5]
l_plus_3 = []
for i in range(len(l)):
l_plus_3.append(l[i] + 3)
``````
``````# With an array
a = np.array(l)
a_plus_3 = a + 3
``````

If you notice from the top, l is a variable type `list`, The reason why we have `a = np.array(l)` is to convert the list to numpy array before we perform the operation on it. The designer of the program just decided to use the list that was earlier declared. It could have also been that we create a new numpy array. And if the latter is the case, we wont need to have the line `a = np.array(l)`. For example

`my_array = np.array([1, 2, 3, 4, 5])`

``````#add 2 to each element in the array

my_array_plus_2 = my_array + 2

print(my_array_plus_2)
``````

`array([3, 4, 5, 6, 7])`

I hope this is clear