Introduction
Linear Algebra Basics
Array Fundamentals
Working with multidimensional arrays
Our example dataset and basic plotting
ndarray methods
Array Axes
Vectorized Computing
Universal Functions (ufuncs)
Advanced array manipulation
Randomness
Selected Topics in Mathematics and Statistics

Creating 1-dimensional arrays

The easiest way to create an array is to pass a list to NumPy’s main utility to create arrays, np.array:

a = np.array([1, 2, 3])

The array function will accept any Python sequence. Think of lists, sets, tuples, or even a range. The function accepts several optional keyword arguments, and we will discuss two of them here: copy and dtype.

The copy argument

The copy argument states whether to make a copy of the input object. When copy is True, any changes in the resulting array will not change the input object. However, if it is False, changes in the array can change the input object.

When using lists to make arrays, NumPy will always copy the object regardless of the argument’s value; for example:

lst = [1, 2, 3]
a = np.array(lst, copy=False)
print(a)
# array([1, 2, 3])

If we change the array, the list will stay the same since NumPy copied the values, despite our copy=False argument:

a[0] = 0
print(lst)
# [1, 2, 3]

Now we will create the same list but with another NumPy array as input:

a_in = np.array([1, 2, 3])
a = np.array(a_in, copy=False)
a

Let’s see what happens if we change the resulting array:

a[0] = 0
print(a)
# array([0,2,3])
print(a_in)
# array([0,2,3])

Both arrays changed because we set the copy option to False.

You can test this for yourself using the following code crumb:

Change the copy argument and see what happens!

The dtype argument

Another commonly used argument is dtype, indicating the data type of the elements of this array explicitly. In the next lesson, you will learn about the available data types. One of them, np.int16, is the smallest available integer type, taking up way less space (just two bytes) than a regular Python integer.

Other 1D array-creation functions

Besides np.array, several other functions are mostly thin wrappers around np.array, but with some specific options. E.g.:

  • np.asarray(a) will return the input without copying if the input is a compatible NumPy array (copy=False)
  • np.copy(a): the input is always copied (copy=True)
  • np.fromiter(iter, dtype): creates a new array from an iterable object. This function requires you to set a dtype explicitly (a topic of the following lesson)

Head over to the official documentation to learn about all the options and other array creation functions.

Lesson Content