NumPy (Numerical Python) is one of the most powerful libraries for numerical computations, data manipulation, and analysis in Python. At the core of NumPy is the ndarray, a multi-dimensional or N-dimensional array that allows to store and manipulate large datasets efficiently. NumPy provides several ways to create arrays, from simple ones to more complex multi-dimensional structures.
In last tutorial, we learned about Key Features of NumPy Arrays in Python. This tutorial will guide us through the process and different ways to create NumPy Arrays in Python. We will learn about various methods and options available for constructing NumPy arrays.
numpy.array()
Function to Create NumPy Arrays using Lists, Tuples and Arrays
The numpy.array()
function is a basic way to initialize an array in NumPy. The numpy.array()
function is used to create NumPy arrays from any sequence-like objects, such as tuples, lists, or other array-like structure. Let’s understand the basic syntax of numpy.array()
function.
numpy.array()
Function
numpy.array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, like=None)
numpy.array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, like=None)
- object – This is an array-like object which exposes the array interface and
__array__
method returns an array or any sequence. Generally, the input object is given as a list, tuple, nested list or array. - dtype (optional) – This is the data-type for the array like int, float, and complex. If the data type is not specified, NumPy will try to use the default
dtype
, that can represent the elements of an array. - copy (optional) – By default it is
True
. IfTrue
, then array elements will be copied, else ifFalse
a copy will only be made if object’s__array__
method returns a copy - order (optional) – Possible values are from
[K, A, F, C]
.C
order means row major andF
(Fortran) order means column major. ForK
andA
option,C
andF
order is used based on copy parameter isTrue
orFalse
. When the Object is an array following holds:
order | no copy | copy=True |
---|---|---|
K | unchanged | F and C order preserved |
A | Unchanged | F order if input is F, C order if input is C |
F | F order | F order |
C | C order | C order |
- subok (optional) – If
True
, return sub-classes of ndarray. Otherwise, return the base class of ndarray. - ndim (optional) – Specifies the minimum number of dimensions that the resulting array should have.
- like (optional) – Reference object to allow the creation of arrays which are not NumPy arrays
numpy.array()
– Create NumPy Array using List with Homogeneous Elements
Python list can be used as an initial input to create NumPy arrays. When a Python list passes to a numpy.array()
function, the list is converted into a structured array format.
import numpy as np # Import numpy library alias name np
list_1 = [15, 32, 43, 44, 65] # list with integer elements
arr_1 = np.array(list_1)
print(arr_1) # Output => [15 32 43 44 65] => Array all elements are integer
numpy.array()
– Create NumPy Array using List with Heterogeneous Elements
If Python list with different data-type elements is passed to numpy.array()
function, it gets converted into the homogeneous data-type elements for resulting NumPy array.
import numpy as np # Import numpy library alias name np
list_2 = [11, 22.3, 33, 55] # list with integer and float data-type elements
array_2 = np.array(list_2)
print(array_2) # Output => [11. 22.3 33. 55. ] => Array all elements are float
list_3 = [10, 'a', 22.4, 51] # list with integer, string and float data-type elements
array_3= np.array(list_3)
print(array_3) # Output => ['10' 'a' '22.4' '51'] => Array all elements are string
list_4 = [11, 2, 34, 76] # list with integer elements
array_4 = np.array(list_4, dtype='U16') # datatype of an array can be defined explicitly
print(array_4) # Output => ['11' '2' '34' '76'] => Array all elements are string
In this example program, we have created NumPy array using list with heterogeneous elements.
list_2 = [11, 22.3, 33, 55]
has integer and float data-type elements.np.array(list_2)
results in NumPy array[11. 22.3 33. 55. ]
which has all float elements.list_3 = [10, 'a', 22.4, 51]
has integer, string and float data-type elements.np.array(list_3)
results in NumPy array['10' 'a' '22.4' '51']
which has all string elements.list_4 = [11, 2, 34, 76]
has all integer data-type elements.np.array(list_4, dtype='U16')
we are explicitly defining the array data-type, which results in NumPy array['11' '2' '34' '76']
with all string elements.
NumPy Arrays vs Python List
NumPy Array | Python List |
---|---|
Implemented in C programming language and Optimized for numerical operations | Python lists are not optimized for numerical operations, mathematical operations is slower |
NumPy arrays are homogeneous, meaning they store elements of the same data type (e.g., all integers or all floats). | Python lists are heterogeneous, meaning they can store elements of different data types (e.g., integers, strings, floats, etc.). |
Use less memory than Python lists because they are fixed in size and store data of a single type. | More memory-intensive because they allow dynamic resizing and store references to objects |
Provides many built-in mathematical functions and supports vectorized operations (operations on entire arrays without using loops) | Python lists do not support vectorized operations natively. Mathematical operations on lists require looping through the elements |
Supports multi-dimensional arrays (e.g., 2D, 3D arrays) natively | Represent multi-dimensional arrays using nested lists |
Ideal for representing matrices and higher-dimensional data structures | Not efficient for matrix operations and higher-dimensional data manipulation. |
NumPy is used extensively in fields such as scientific computing, data analysis, machine learning, and image processing | Python lists are better suited for general-purpose programming, where the data may not need to be numeric or handled in large quantities. |
Why use Python list to create NumPy array
- Python lists are heterogeneous data-type, which can support different data type elements
- Python lists can be easily used to initialize NumPy array
- NumPy ensures all elements converted to homogeneous data-type.
numpy.array()
– Create 2-D NumPy Array using Nested List
n-Dimensional NumPy Arrays can be created using nested lists.
import numpy as np
nested_list = [[11, 22.3, 33], [41, 52, 63]] # nested list with integer and float data-type elements
arr_2d = np.array(nested_list)
print(arr_2d)
# Output => 2-D Array all elements are float
# [[11. 22.3 33. ]
# [41. 52. 63. ]]
nested_list_2 = [['a', 22.3, 33], [41, 52, 63]] # nested list with integer, string and float data-type elements
string_array_2d= np.array(nested_list_2)
print(string_array_2d)
# Output => 2-D Array all elements are string
# [['a' '22.3' '33']
# ['41' '52' '63']]
In this program, we have created 2-dimensional array using nested list.
nested_list = [[11, 22.3, 33], [41, 52, 63]]
has integer and float data-type elements.np.array(nested_list)
results in NumPy array[[11. 22.3 33. ][41. 52. 63. ]]
which has all float elements.nested_list_2 = [['a', 22.3, 33], [41, 52, 63]]
has integer, string and float data-type elements.np.array(nested_list_2)
results in NumPy array[['a' '22.3' '33']['41' '52' '63']]
which has all string elements.
numpy.array()
– Create NumPy Array using Tuple
Python sequences like Tuple can be used as an initial input to create NumPy arrays. When a Python Tuple passes to a numpy.array()
function, the tuple is converted into a structured array format.
import numpy as np
integer_tuple = (23, 34, 367, 76) # tuple with all integer data-type elements
array_using_tuple = np.array(integer_tuple) # Create NumPy array using Tuple
print(array_using_tuple) # Output => [ 23 34 367 76]
float_tuple = (11, 22.3, 33, 55) # tuple with integer and float data-type elements
float_array = np.array(float_tuple) # Create NumPy array using Tuple
print(float_array) # Output => [11. 22.3 33. 55. ] => Array all elements are float
string_float_tuple = [10, 'a', 22.4, 51] # tuple with integer, string and float data-type elements
string_array = np.array(string_float_tuple)
print(string_array) # Output => ['10' 'a' '22.4' '51'] => Array all elements are string
In this example program, we have created NumPy array using tuple with heterogeneous elements.
integer_tuple = (23, 34, 367, 76)
has only integer data-type elements.np.array(integer_tuple)
results in NumPy array[ 23 34 367 76]
which has all integer elements.float_tuple = (11, 22.3, 33, 55)
has integer and float data-type elements.np.array(float_tuple)
results in NumPy array[11. 22.3 33. 55. ]
which has all float elements.string_float_tuple = [10, 'a', 22.4, 51]
has integer, string and float data-type elements.np.array(string_float_tuple)
results in NumPy array['10' 'a' '22.4' '51']
which has all string elements.
numpy.array()
– Create 2-D NumPy Array using Nested Tuple
import numpy as np
nested_tuple = ((45, 67.3, 53), (86, 65, 23)) # nested tuple with integer and float data-type elements
arr_2d = np.array(nested_tuple)
print(arr_2d)
# Output => 2-D Array all elements are float => [[45. 67.3 53. ][86. 65. 23. ]]
nested_tuple_2 = (('s', 22.3, 53), (86, 65, 23)) # nested tuple with integer, string and float data-type elements
string_array_2d= np.array(nested_tuple_2)
print(string_array_2d)
# Output => 2-D Array all elements are string => [['s' '22.3' '53']['86' '65' '23']]
nested_tuple_3 = (['s', 22.3, 86], [12, 93, True]) # nested tuple with list elements
array_2d= np.array(nested_tuple_3)
print(array_2d)
# Output => 2-D Array all elements are string => [['s' '22.3' '86']['12' '93' 'True']]
In this program, we have created 2-dimensional array using nested tuple.
nested_tuple = ((45, 67.3, 53), (86, 65, 23))
has integer and float data-type elements.np.array(nested_tuple)
results in NumPy array[[45. 67.3 53. ][86. 65. 23. ]]
which has all float elements.nested_tuple_2 = (('s', 22.3, 53), (86, 65, 23))
has integer, string and float data-type elements.np.array(nested_tuple_2)
results in NumPy array[['s' '22.3' '53']['86' '65' '23']]
which has all string elements.nested_tuple_3 = (['s', 22.3, 86], [12, 93, True])
is a nested tuple with list elements.np.array(nested_tuple_3)
results in NumPy array[['s' '22.3' '86']['12' '93' 'True']]
which has all string elements.
numpy.array()
– Create NumPy Array using Python Array
import array # import Python array module
import numpy as np
python_integer_array = array.array('i', [1, 2, 3, 4, 5]) # Python array with integer numbers
numpy_integer_array = np.array(python_integer_array) # NumPy array with integer numbers
print(numpy_integer_array)
# Output => [1 2 3 4 5]
python_float_array = array.array('f', [65.34, 87.22, 12.22, 54.45, 86.46]) # Python array with float numbers
numpy_float_array = np.array(python_float_array) # NumPy array with float numbers
print(numpy_float_array)
# Output => [65.34 87.22 12.22 54.45 86.46]
python_bool_array = array.array('b', [True, False, True, False]) # Python array with boolean values represented as 0 or 1
numpy_bool_array = np.array(python_bool_array) # NumPy array with boolean values
print(numpy_bool_array)
# Output => [1 0 1 0]
In this program, we have created NumPy arrays using the standard Python arrays. np.array()
function takes the data-type same as the type of Python array.
array.array('i', [1, 2, 3, 4, 5])
creates a standard Python array with integer data-type elements.np.array(python_integer_array)
creates a NumPy array with the integer data-type elements.array.array('f', [65.34, 87.22, 12.22, 54.45, 86.46])
creates a Python array with float data-type elements.np.array(python_float_array)
results in NumPy array with float data-type elements.array.array('b', [True, False, True, True, False])
creates a Python array with boolean data-type elements. Boolean values are converted to its binary representation,True=1
andFalse=0
.np.array(python_bool_array)
results in NumPy array with integer data-type elements.
Conclusion
the numpy.array()
function is a powerful tool for creating NumPy arrays from various data structures, such as lists, tuples, and Python arrays, enabling users to perform efficient data manipulation. Through the examples provided, we saw how to create NumPy arrays from lists with homogeneous and heterogeneous elements, demonstrating how NumPy handles different data types and shapes. We also explored creating 2-D arrays using nested lists and tuples, showcasing the flexibility of NumPy in working with multi-dimensional data.
Furthermore, we examined how to convert Python arrays into NumPy arrays, making it easy to integrate NumPy into existing Python workflows. By mastering these techniques, users can leverage the full potential of NumPy for a wide range of scientific and numerical computing tasks.
Code snippets and programs related to numpy.array()
: Create NumPy Arrays using Lists, Tuples and Arrays, can be accessed from GitHub Repository. This GitHub repository all contains programs related to other topics in NumPy tutorial.
Related Topics
- NumPy Array Attributes | ndarray Attributes (with Example Programs)NumPy (Numerical Python) is a powerful library for numerical computing in Python. It provides support for large multidimensional arrays and matrices, and it also provides a collection of mathematical functions to operate on these arrays. Understanding the attributes of NumPy arrays is essential for efficiently working with them. In previous articles, we learned about NumPy…
- np.logspace(): Create Array of Evenly Spaced Numbers on Logarithmic Scale (with Example Programs)NumPy is a powerful Python library for numerical computing, and np.logspace() is one of the powerful function to create array of evenly spaced numbers on logarithmic scale. In previous tutorials, we learned about Key Features of NumPy Arrays in Python. This tutorial will provide a step-by-step guide to understand how to use np.logspace() effectively, with examples.…
- np.linspace(): Create Arrays with Evenly Spaced Numbers in NumPy (with Example Programs)NumPy is a powerful Python library for numerical computing, and np.linspace() is one of the most useful functions for generating arrays of evenly spaced values within a specified range. In previous tutorials, we learned about Key Features of NumPy Arrays in Python. This tutorial will provide a step-by-step guide to understand how to use np.linspace() effectively,…
- numpy.arange(): Create Array of Evenly Spaced Numbers within a Range (with Example Programs)NumPy library provides various functions to create arrays with evenly spaced numbers within range. In previous tutorials, we learned about Key Features of NumPy Arrays in Python. In this tutorial, we will learn to create NumPy arrays using numpy.arrange() function. numpy.arange() to Create Array of Evenly Spaced Numbers within a Range numpy.arange() is used to create…
- Create Arrays with Predefined Values using np.zeros(), np.ones(), np.full() and np.empty()Create Arrays with Predefined Values NumPy library provides various functions to create arrays with predefined values. While creating an array, these NumPy functions helps to initialize the arrays with initial values. In last tutorial, we learned about Key Features of NumPy Arrays in Python. In this article, we will learn about 4 functions to create…