What is the array tolist() function in Python?
Overview
An array is a collection of multiple values, items, or elements of the same datatype in a single variable.
The tolist() function is used to convert a given array to an ordinary list with the same items, elements, or values.
Syntax
The syntax of the tolist() function is given below:
array.tolist()
Parameters
The tolist() function does not take any parameters.
Return value
The tolist() function returns a list that contains the same items of the original array.
Example
Let’s see an example.
# importing the array moduleimport array as arr# creating an integer data type arrayx = arr.array('i', [1,2,3,4,5,6,7])# using the tolist() function to change the array to a listy = x.tolist()# Printing the listprint(y)
Explanation
- Line 1: We import the array module.
- Line 5: We create an array object.
- Line 8: We convert the array to a list.
- Line 11: We print the list.