Creating an array from a list

To create an array from an explicit list, use the following code:

x = np.array([2, 3.5, 5.2, 7.3])

This will assign to x the following array object:

array([ 2. , 3.5, -1. , 7.3, 0. ])

Notice that integer array entries are converted to floating point values. NumPy arrays are homogeneous, that is, all elements of an array must have the same type. Upon creation, elements in the input list are converted to a common type by a process known as casting. In the preceding example, all elements are cast to floats.

To create a multidimensional array, use a list of lists:

A = np.array([[1, -3, 2],[2, 0, 1]])

This creates the array:

array([[ 1, -3, 2], 
[ 2, 0, 1]])

The array elements in this example are integers. Creating arrays with more than two dimensions using this method is unwieldy, and is not recommended. Instead of a list literal, a list comprehension can be used for initialization:

x = np.array([i**2 for i in range(5)])

This creates an array containing the squares of the integers in the range of 0 to 4:

array([ 0,  1,  4,  9, 16])

This is not the most efficient way to generate this array in NumPy. We will later see how to use vectorized functions to generate this array very efficiently.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset