Home »
Python
Convert an array to the list using array.tolist() in Python
Learn how to convert an array to the list using array.tolist() in Python.
By IncludeHelp Last updated : January 14, 2024
Problem statement
Given an array with some elements and we have to convert them to the list using array.tolist() in Python.
Creating an array
To create an array - we are using "array" module in the program by importing using "import array as arr" (Read more: Create array using array module).
Converting array to the list with same elements
To convert an array to the list - we use tolist() methods of "array" class, it returns the list with the same elements.
Syntax
list = array.tolist()
Algorithm
- Here, we are declaring an array of signed int named a (by using i type_code) and initializing it with the elements [10, -20, 30, -40, 50]
- Then, we are printing the type of elements of a and elements of array a
- Then, we declared an empty list named list1
- Then, we are converting the array to the list with some elements
- Then, we are printing the type of list1 and elements of list1
Python program to convert an array to the list
# importing array class to use array
import array as arr
# declare array
a = arr.array ("i", [10, -20, 30, -40, 50])
# print the type of a
print ("type of a: ", type(a))
# print array
print ("a is:", a);
# declare an empty list
list1 = list()
# convert array and assign to the list
list1 = a.tolist()
# print type of list1
print ("Type of list1: ", type(list1))
# print list
print ("list1 is: ", list1)
Output
type of a: <class 'array.array'>
a is: array('i', [10, -20, 30, -40, 50])
Type of list1: <class 'list'>
list1 is: [10, -20, 30, -40, 50]