Tuesday, January 21, 2025
HomeProgrammingNumpy.array() In Python

Numpy.array() In Python

In Python, numpy.array() is a function provided by the NumPy library to create arrays, which are more efficient for numerical operations than Python’s native lists. The numpy.array() function can create an array from a variety of input types like lists, tuples, and other sequences.

Here’s a basic example of how to use numpy.array():

import numpy as np

# Creating a numpy array from a list
arr = np.array([1, 2, 3, 4, 5])

print(arr)

Key Features of numpy.array():

  1. Multidimensional Arrays: You can create multidimensional arrays (matrices) as well.
    arr = np.array([[1, 2, 3], [4, 5, 6]])
    print(arr)
    
  2. Array Data Types: NumPy arrays support various data types, such as integers, floats, and complex numbers. You can specify the data type using the dtype argument.
    arr = np.array([1.1, 2.2, 3.3], dtype=np.float32)
    print(arr)
    
  3. Shape and Size: The .shape and .size attributes allow you to view the dimensions and total number of elements in the array.
    print(arr.shape)  # Output: (2, 3) for a 2x3 matrix
    print(arr.size)   # Output: 6
    
  4. Default Data Type: If you don’t specify a data type, NumPy tries to infer the most appropriate one, usually converting all elements to the highest type (e.g., float64 for mixed integer and float input).
See also  What is the Average Speed of Man Running?

Example:

import numpy as np

# 1D Array
arr_1d = np.array([1, 2, 3, 4])
print(arr_1d)

# 2D Array (Matrix)
arr_2d = np.array([[1, 2], [3, 4]])
print(arr_2d)

# Array with dtype specified
arr_float = np.array([1, 2, 3], dtype=np.float64)
print(arr_float)

Output:

[1 2 3 4]
[[1 2]
 [3 4]]
[1. 2. 3.]

In summary, numpy.array() is an efficient and versatile way to work with arrays, particularly for numerical operations, in Python.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x