In this post, you will learn how to convert an array to a list using Python. Show Nội dung chính
Nội dung chính
In Python, array and list are mostly used data structure. An array is a container which can hold a fixed number of items, and these items should be of the same type. A list is a sequence of indexed and ordered values. It contains a list of any type of data objects with a comma separated and enclosed within a square bracket. In the development process, we may come to the situation where we need to convert an array to a list. Python provides in-build method tolist() to convert an array to a list. If the array is one-dimensional, a list with the array elements is returned, and if the array is multi-dimensional, a nested list is returned. Converting array to list using numpy tolist() methodWe can convert an array to the list of data elements with the help of ndarray.tolist() method. The numpy ndarray object has a handy tolist() method that can be used to convert the respect numpy array to a list. This method doesn't accept any argument and returns a copy of the array data as a Python list. In the given example, we have converted the one-dimensional numpy array to a list. import numpy as np arr = np.array([2,4,6]) numpy_arr = np.array(arr) # printing my_array print("Array - \n") print(numpy_arr) # convert array to list numpy_list = numpy_arr.tolist() print("List - ",numpy_list) Output of the above code - Array - [2 4 6] List - [2, 4, 6]Converting multi-dimensional array to listIn the given example, we have converted a multidimensional array to the list of data elements with the help of tolist() method. import numpy as np arr = np.array([[2,4,6],[3,1,4],[5,3,6]]) numpy_arr = np.array(arr) # printing my_array print("Array - \n") print(numpy_arr) # convert array to list numpy_list = numpy_arr.tolist() print("List - ",numpy_list) Output of the above code - Array - [[2 4 6] [3 1 4] [5 3 6]] List - [[2, 4, 6], [3, 1, 4], [5, 3, 6]]Converting array to list using array classHere, first we are importing an array class to use an array. Then, we convert an array to the list of data elements with the help of tolist() method. import array as arr # declare array x = arr.array ("i", [5, -4, -50, 35, 11]) # declare an empty list y = list() # convert array and assign to the list y = x.tolist() # print list print ("Created list : ", y) Output of the above code - Created list : [5, -4, -50, 35, 11]Related Articles Python Numpy Array Shape During programming, there will be instances when you will need to convert existing lists to arrays in order to perform certain operations on them (arrays enable mathematical operations to be performed on them in ways that lists do not).
numpy provides us with two functions to use when converting a list into an array:
This function of the numpy library takes a list as an argument and returns an array that contains all the elements of the list. See the example below: import numpy as np my_list = [2,4,6,8,10] my_array = np.array(my_list) # printing my_array print my_array # printing the type of my_array print type(my_array) This function calls the numpy.array() function inside itself. See the definition below: def asarray(a, dtype=None, order=None): return array(a, dtype, copy=False, order=order)
This means that np.array() will make a copy of the object (by default) and convert that to an array, while np.asarray() will not. The code below illustrates the usage of np.asarray(): import numpy as np my_list = [2,4,6,8,10] my_array = np.asarray(my_list) # printing my_array print my_array # printing the type of my_array print type(my_array) method ndarray.tolist()¶Return the array as an a.ndim-levels deep nested list of Python scalars. Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible builtin Python type, via the item function. If a.ndim is 0, then since the depth of the nested list is 0, it will not be a list at all, but a simple Python scalar. Parameters none Returns yobject, or list of object, or list of list of object, or …The possibly nested list of array elements. Notes The array may be recreated via a = np.array(a.tolist()), although this may sometimes lose precision. Examples For a 1D array, a.tolist() is almost the same as list(a), except that tolist changes numpy scalars to Python scalars: >>> a = np.uint32([1, 2]) >>> a_list = list(a) >>> a_list [1, 2] >>> type(a_list[0]) <class 'numpy.uint32'> >>> a_tolist = a.tolist() >>> a_tolist [1, 2] >>> type(a_tolist[0]) <class 'int'> Additionally, for a 2D array, tolist applies recursively: >>> a = np.array([[1, 2], [3, 4]]) >>> list(a) [array([1, 2]), array([3, 4])] >>> a.tolist() [[1, 2], [3, 4]] The base case for this recursion is a 0D array: >>> a = np.array(1) >>> list(a) Traceback (most recent call last): ... TypeError: iteration over a 0-d array >>> a.tolist() 1 |