Skip to content

Latest commit

 

History

History
70 lines (70 loc) · 3.36 KB

File metadata and controls

70 lines (70 loc) · 3.36 KB

< Previous       Next >


You've successfully created NumPy arrays — now see what you can do to them!
Create two lists and fill them all with 5 ones.
1. In your notebook for numpy, create two lists:
num1 = [1, 1, 1, 1, 1]
num2 = [1, 1, 1, 1, 1]
Next, add the lists together with the + operator.
2. In the next cell, add:
num1 + num2
3. Run the program.
You should see 10 ones print out.
Rather than extending the list, sometimes you might need to add values in the array together. In the previous example, how would you get the result [2, 2, 2, 2, 2]?
To accomplish this, you'll need a for loop. You can use a for loop to access each index in the array. To loop through all the values in the array you'll need to use len(num1).
len(arrayName) # returns the number of elements in that array.
You'll also need a third new array to hold the new sums.
arrayName.append(value) # adds element to the array.


You'll first create a holder list called num3. From there, use a for loop to loop len(num1) times to access each value in the two arrays.
As the two values are added, they are appended to num3.
num1 = [1, 1, 1, 1, 1]
num2 = [1, 1, 1, 1, 1]
num3 = [ ] #create a holder list
for i in range(len(num1)): #a for loop that loops over every value in the loop based on the side of the array num3.append(num1[i] + num2[i]) #add the sum of the values at the ith position of the arrays and save them to num3
print(num3)
While this method works, NumPy arrays let you do the same thing in one line.

Addition

1. Create two NumPy arrays with the same values and numbers:
arr1 = np.array([1, 1, 1, 1, 1])
arr2 = np.array([1, 1, 1, 1, 1])
2. Add the arrays together:
print(arr1 + arr2)
3. Run the program.
You should see the array printed with values added together. As long as both numpy arrays are the same size, you can add them together this way.
[1, 2, 3] + [1, 2, 3] would become [2, 4, 6]. If you had [1,2] + [1,2,3] it would return an error because the size of the arrays are different.

Multiplication

The same goes for multiplication. Replacing the plus sign in the previous example gives you the product of both arrays:
[1, 2, 3] * [1, 2, 3] will become [1, 4, 9].
This can be done for subtraction and division as well.

Adding a Number to an Array

You can add an individual number to the other values in an array using an addition operator ( + ):
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([2, 3, 4, 5, 6])
print(arr1+5)

Recap

You can use the + operator to combine two regular python lists into a single list. Numpy arrays let you use the + operator to add two same-size arrays together, adding each element in matching locations together. Using the + operator with a Numpy array and a single value will add that value to every element in the array.