0
0
NumPydata~5 mins

np.array() from Python lists in NumPy

Choose your learning style9 modes available
Introduction

We use np.array() to turn regular Python lists into arrays that are easier to work with for math and data tasks.

You have a list of numbers and want to do math on all of them quickly.
You want to store data in a format that many data science tools understand.
You need to perform operations like addition or multiplication on whole lists at once.
You want to use functions that only work with arrays, not lists.
Syntax
NumPy
import numpy as np

# Create a numpy array from a Python list
array_name = np.array(python_list)

The input to np.array() is usually a Python list or a list of lists for multi-dimensional arrays.

The output is a numpy array, which supports fast math and many useful functions.

Examples
This creates a one-dimensional array from a simple list of numbers.
NumPy
import numpy as np

# Example 1: 1D array from a list
numbers_list = [1, 2, 3, 4]
numbers_array = np.array(numbers_list)
print(numbers_array)
This creates a two-dimensional array (like a table) from a list of lists.
NumPy
import numpy as np

# Example 2: 2D array from a list of lists
matrix_list = [[1, 2], [3, 4]]
matrix_array = np.array(matrix_list)
print(matrix_array)
Creating an array from an empty list results in an empty numpy array.
NumPy
import numpy as np

# Example 3: Empty list
empty_list = []
empty_array = np.array(empty_list)
print(empty_array)
This creates an array with just one element.
NumPy
import numpy as np

# Example 4: List with one element
single_element_list = [42]
single_element_array = np.array(single_element_list)
print(single_element_array)
Sample Program

This program shows how to convert a Python list to a numpy array and prints both to compare.

NumPy
import numpy as np

# Create a Python list
python_list = [10, 20, 30, 40]
print("Original Python list:", python_list)

# Convert the list to a numpy array
numpy_array = np.array(python_list)
print("Converted numpy array:", numpy_array)

# Show the type to confirm
print("Type of original list:", type(python_list))
print("Type of numpy array:", type(numpy_array))
OutputSuccess
Important Notes

Time complexity: Creating an array from a list takes O(n) time, where n is the number of elements.

Space complexity: The array uses space proportional to the number of elements, similar to the list.

A common mistake is to think numpy arrays behave exactly like lists; arrays support element-wise math, unlike lists.

Use np.array() when you want to do math or data operations efficiently on collections of numbers.

Summary

np.array() converts Python lists into numpy arrays for easier math and data work.

Arrays support fast, element-wise operations that lists do not.

Use this to prepare data for analysis or scientific computing.