 # How To Create NumPy Arrays In Different Ways

While the primary way to create NumPy arrays is the function numpy.array(), this library also provides plenty of other options. This tutorial will give you a quick look at these methods and their usage.

## Create NumPy Arrays

### numpy.array()

The easiest way to create a NumPy array (ndarray) with numpy.array() is to pass an array or array-like object to it without any arguments.

Here is an example of using this function to create an array from a list:

import numpy as np
a = (1, 2, 3, 4)
b = np.array(a)
print(b) # [1 2 3 4]
type(b) # <class 'numpy.ndarray'>


When you give it an unnested list, numpy.array() will return a 1D array containing all the elements of that list. Remember to load the NumPy library first, or you will see the error “name ‘array’ is not defined”.

A tuple can also work in place of the list above. At the end of the day, they are similar data structures. The main difference is that lists are mutable, while tuples aren’t.

When you provide a tuple with the same shape and elements, the returned NumPy array will be the same:

import numpy as np
a = [1, 2, 3, 4]
b = np.array(a)
print(b) # [1 2 3 4]


To create higher-dimensional arrays, you can provide numpy.array() with nested data structures. In this example, we use a nested list to create a 2D ndarray:

import numpy as np
a = [[1, 2], [3, 4]]
b = np.array(a)
print(b) # [[1 2]
#  [3 4]]

b.shape  # (2, 2)


The list here has two elements, each of which is a list of two elements. The numpy.array() function detects this and produces a 2D array. It has two rows and two columns – you can verify this shape with the shape property.

You can even create 2D or higher-dimensional arrays with an unnested list. The optional argument ndmin of the numpy.array() function controls the minimum number of dimensions you want the returned array to have.

For example, you can force numpy.array() to create a 2D array by set ndmin to 2:

import numpy as np
a = [1, 2, 3, 4]
b = np.array(a, ndmin = 2)
print(b) # [[1 2 3 4]]


### Other Methods

In addition to numpy.array(), NumPy also comes with a whole host of other functions for array creation. They are designed to address the different needs of NumPy users.

You can, for example, create empty arrays or arrays with predefined content with built-in NumPy functions.

In particular, use numpy.zeros() and numpy.ones() when you want to create an array filled only with zeros and ones, respectively.

>>> np.zeros([2, 2])
array([[0., 0.],
[0., 0.]])
>>> np.ones([2, 2])
array([[1., 1.],
[1., 1.]])

The two commands above create (2, 2) arrays that contain only zeros and ones. Keep in mind that you need to provide the resulting array’s shape in a tuple.

## Summary

There are multiple ways to create NumPy arrays. You can use numpy.array() to convert a Python data structure like a list or tuple to an array. Other functions coming with NumPy can help you initialize arrays in other ways.