Wednesday, December 25, 2024
Google search engine
HomeLanguagesPython | Convert list to Python array

Python | Convert list to Python array

Sometimes while working in Python we can have a problem in which we need to restrict the data elements to just one type. A list can be heterogeneous, can have data of multiple data types and it is sometimes undesirable. There is a need to convert this to a data structure that restricts the type of data.

Convert List to Array Python

Below are the methods that we will cover in this article:

  • Using array() with data type indicator 
  • Using numpy.array() method 

Convert a list to an array using numpy.array()

This task can be easily performed using the array() function. This is an inbuilt function in Python to convert to an array. The data type indicator “i” is used in the case of integers, which restricts data type. 

Python3




# Using array() + data type indicator
from array import array
 
# initializing list
test_list = [6, 4, 8, 9, 10]
 
# printing list
print("The original list : " + str(test_list))
 
# Convert list to Python array
# Using array() + data type indicator
res = array("i", test_list)
 
# Printing result
print("List after conversion to array : " + str(res))


Output

 
The original list : [6, 4, 8, 9, 10]
List after conversion to array : array('i', [6, 4, 8, 9, 10])

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Convert Python List to NumPy Arrays using numpy.array() 

Converts a Python list to a Python array using the numpy.array() function. It imports the numpy module, initializes a list named test_list, and prints the original list. Then, the numpy.array() function is used to convert test_list to a Python array and store the result in the res variable. Finally, it prints the resulting Python array.

Python3




#Using numpy.array()
import numpy as np
 
#initializing list
test_list = [6, 4, 8, 9, 10]
 
#printing list
print("The original list : " + str(test_list))
 
#Convert list to Python array using numpy.array
res = np.array(test_list)
 
#Printing result
print("List after conversion to array : " + str(res))


Output:

The original list : [6, 4, 8, 9, 10]
List after conversion to array : [ 6  4  8  9 10]

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) as the Python array created by numpy.array() stores the same data as the original list.

RELATED ARTICLES

Most Popular

Recent Comments