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 than 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
# initializing list lst = [1, 7, 0, 6, 2, 5, 6]
# converting list to array arr = numpy.array(lst)
# displaying list print ("List: ", last)
# displaying array print ("Array: ", arr)
Output:
List: [1, 7, 0, 6, 2, 5, 6] Array: [1 7 0 6 2 5 6]
- Using numpy.asarray()
# importing library
import numpy
# initializing list lst = [1, 7, 0, 6, 2, 5, 6]
# converting list to array arr = numpy.asarray(lst)
# displaying list print ("List:", last)
# displaying array print ("Array: ", arr)
Output:
List: [1, 7, 0, 6, 2, 5, 6] Array: [1 7 0 6 2 5 6]