Curriculum
Course: Mastering NumPy
Login
Text lesson

Creating NumPy Arrays

In this lesson, you will learn

  • Creating NumPy Arrays

 

Creating NumPy Arrays

NumPy is an N-dimensional array type called ndarray that contains items of the same types.

numpy.array() – A built-in NumPy function that creates a NumPy array.

 

Example-1: Creating NumPy Array

A= np.array([1, 2, 3])
B= np.array((4, 5, 6))
print(A)
print(B)

Output

[1 2 3]
[4 5 6]

 

Upcasting

A=np.array([1, 2, 3.0])
print(A)

Output

[1. 2. 3.]

 

Creating 2-D NumPy Array

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

 

Note: You can create an ndarray from a regular Python list or tuple using the numpy.array() function.

 

Example-1: Use a list to create a NumPy array

my_list = [1, 2, 3, 4]           # Define a list
my_array = np.array(my_list)     # Pass the list to np.array()
print(my_array)                  # display array

 

Output

[1 2 3 4]

 

Example-2: Use a tuple to create a NumPy array:

import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr) 

 

Output

[1 2 3 4 5]

 

Creating an Array of float Datatype

Example

my_list = [1, 2, 3, 4]             # Define a list
my_array = np.array(my_list, dtype=float)   
print(my_array)                    # display array

 

Output

[1. 2. 3. 4.]

 

Creating an Array of Complex Datatype

Example

my_list = [1, 2, 3, 4]             # Define a list
my_array = np.array(my_list, dtype=complex)
print(my_array)                    # display array

 

Output

[1.+0.j 2.+0.j 3.+0.j 4.+0.j]

 

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review