Start learning free

LESSON 1 OF 165 · MACHINE LEARNING: NUMPY

Your First Array

Practice

numpy is Python's library for working with many numbers at once. Its main tool is the array: a row of numbers, like a list, where math works on every item at once. You make one with np.array(a_list), which gives back an array with the same numbers in the same order.

On a plain list, * 2 repeats the list and + 1 is an error, so changing every item takes a loop. On an array, * and + work on each item and give back a new array, with no loop:

import numpy as np

stock = np.array([3, 0, 8])
print(stock * 10)   # [30  0 80]
print(stock + 5)    # [ 8  5 13]

An array also knows its size and its type. .shape gives back a tuple with the size: (3,) means one dimension with 3 items. .dtype gives back the type that every item shares: int64 for whole numbers, float64 for numbers with a decimal point. Neither takes brackets: they are values, not functions.

Your program must print:

List * 2: [12, 7, 29, 2, 15, 12, 7, 29, 2, 15]
Array: [12  7 29  2 15]
Doubled: [24 14 58  4 30]
Plus 1: [13  8 30  3 16]
Shape: (5,)
Type: int64

Your task: the starting code already prints price_list * 2, the list repeated. Below that print, turn price_list into an array prices, then print it, prices * 2, prices + 1, its .shape and its .dtype.


Assignment
Follow the Coding Tutorial to turn the list of prices into an array and print what it can do.


Hint
Make the array once and keep it in prices: every later line works on prices, not on the list. .shape and .dtype come without brackets.


STEP 1 OF 6
    Ctrl + Enter to check