Create an array from a list

Lesson 3 Chapter 2

** An array is basically a one- or multi-dimensional grid of values.** In a Numpy array, in particular,

*all values are from the same type (integer, float)*. How we are going to define a Numpy array? For a Numpy array, we have the following definitions:

**Rank**: The number of dimensions an array has.**Shape**: A**tuple**that indicates the number of elements in each dimension. Ex: The shape of an array being as (2,4,10) indicates that we have a three-dimensional array which has 2,4, and 10 elements in the first, second, and third dimension, respectively.

Now let's get started with Python. We start with the most common approach. Let's define create a Numpy array from a list:

# Import Numpy library import numpy as np # Define a Python list mylist = [1, 2, 4, 8] # Create a Numpy array from the list numpy_array = np.array(mylist) print('Array: ', numpy_array)

Array: [1 2 4 8]

What if we *do not define a list and just input the numbers* as below:

# Import Numpy library import numpy as np # Naively input the numbers numpy_array = np.array(1,2,4,8) print('Array: ', numpy_array)

--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-3-6d0f836d151e> in <module>() 2 3 # Naively input the numbers ----> 4 numpy_array = np.array(1,2,4,8) 5 print('Array: ', numpy_array) ValueError: only 2 non-keyword arguments accepted

As you can see above, **Python complains**!!

Now, let's define a ** two-dimensional** array:

# Import Numpy library import numpy as np # Naively input the numbers row1 = [2,4,6,8] row2 = [1,3,5,7] numpy_array = np.array([row1,row2]) print('Array: ', numpy_array) # Get the shape print('Shape: ', numpy_array.shape)

Array: [[2 4 6 8] [1 3 5 7]] Shape: (2, 4)

Let's take a look at the above code once again. We defined a matrix. The argument inside **np.array** is a list that each of its elements is another list (see figure above)! The inside lists denoted as

and **row1**

forms the rows of the matrix and MUST have the same size! **row2****Think why?** That was a simple example to showcase how we can create arrays. I used

method to return the Numpy array shape. The output above shows we have a matrix with two rows and four columns.**.shape**