Convert Python List to numpy Arrays
A list in Python is a linear data structure that can hold heterogeneous elements they do not require to be declared and are flexible to shrink and grow. On the other hand, an array is a data structure which can hold homogeneous elements, arrays are implemented in Python using the NumPy library. Arrays require less memory then list.
The similarity between an array and a list is that the elements of both array and a list can be identified by its index value.
In Python lists can be converted to arrays by using two methods from the NumPy library:
- Using
numpy.array()
# importing library import numpy # initilizing list lst = [1, 7, 0, 6, 2, 5, 6] # converting list to array arr = numpy.array(lst) # displaying list print ("List: ", lst) # displaying array print ("Array: ", arr) |
Output:
List: [1, 7, 0, 6, 2, 5, 6] Array: [1 7 0 6 2 5 6]
numpy.asarray()
# importing library import numpy # initilizing list lst = [1, 7, 0, 6, 2, 5, 6] # converting list to array arr = numpy.asarray(lst) # displaying list print ("List:", lst) # displaying array print ("Array: ", arr) |
Output:
List: [1, 7, 0, 6, 2, 5, 6] Array: [1 7 0 6 2 5 6]
The vital difference between the above two methods is that numpy.array() will make a duplicate of the original object and numpy.asarray() would mirror the changes in the original object.
Recommended Posts:
- Python | Convert Numpy Arrays to Tuples
- Python | Convert mixed data types tuple list to string list
- Python | Convert string List to Nested Character List
- Python | Convert list of string into sorted list of integer
- Python Program to convert List of Integer to List of String
- Python | Convert list of numerical string to list of Integers
- Python | Convert list of string to list of list
- Python | Convert list of tuples to list of list
- Python | Convert Integral list to tuple list
- Python | Convert list of strings to list of tuples
- Python | Convert string enclosed list to list
- Python | Convert 1D list to 2D list of variable length
- Python | Convert list to indexed tuple list
- Python | Convert list of tuples to list of strings
- Python | Convert List of Dictionary to Tuple list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

