In this article we will discuss how to create a Numpy Numpy Array from a sequence like list or tuple etc. Also, how to create a 2D numpy Numpy Array from nested sequence like lists of lists.

To install the python’s numpy module on you system use following command,

To use numpy module we need to import it i.e.

numpy.array()

Python’s Numpy module provides a function numpy.array() to create a Numpy Array from an another array like object in python like list or tuple etc or any nested sequence like list of list,

Arguments:  object is an array like object i.e. list or tuple or any nested sequence like list of list. Other parameters are optional and has default values.

It returns a Numpy Array .

Let’s use this numpy.array() to create Numpy Array objects

Create Numpy Array from a list

To create a Numpy Array from list just pass the list object to numpy.array() i.e.

Output:

Create Numpy Array from a tuple

Similar to above example, we can directly pass the tuple to the numpy.array() to create a Numpy Array object,

Output:

Check type of Numpy Array object

We can also check the type of the created Numpy Array using type() function i.e.

Example:

Output

Check the data type of elements in Numpy Array

Numpy array Numpy Array has a member variable that tells about the datatype of elements in it i.e. ndarray.dtype.

We created the Numpy Array from the list or tuple. While creation numpy.array() will deduce the data type of the elements based on input passed.
But we can check the data type of Numpy Array elements i.e.

Output:

Create 2D Numpy Array from a list of list

Suppose we want to create 2D Numpy Array like Matrix, we can do that by passing a nested sequence in numpy.array() i.e. list of list.
For example,

Output:

Create 1D Numpy Array from list of list

On passing a list of list to numpy.array() will create a 2D Numpy Array by default. But if we want to create a 1D numpy array from list of list then we need to merge lists of lists to a single list and then pass it to numpy.array() i.e.

Output:

Create a Numpy Array from a list with different data type

We can also pass the dtype as parameter in numpy.array(). In that case numpy.array() will not deduce the data type from passed elements, it convert them to passed data type.

For example pass the dtype as float with list of int i.e.

Output:

Complete example is as follows,

Output:

 

 

Click Here to Subscribe for more Articles / Tutorials like this.