Convert an array to the list using array.tolist() in Python

This is in-depth look at turning arrays into lists in Python without losing their core content.

Array in python

“An array is a group of objects that are all placed together. This arrangement enables us to quickly determine the location of each item by just adding some fixed number to an initial value being memory address using which we can reference the earliest item in the collection they all belong to.”

Syntax :

In python, array’s can be declared by using the “array” module. Let us now see it’s syntax:

import array as array_name
  • import : command to import module
  • array : name of the module
  • array_name : name of the array

List in python

The manner in which Python Lists work is similar to that of dynamically sized arrays recognized in other languages, as shown by vector in C++ or ArrayList in Java. For concise explanations, a Python list is a group of stuff put in [ ] with commas between them.

Example :

x = ["Code","speedy"]

print(x)
Output :
["Code","speedy"]

Need for Conversion

The conversion happens often during programming because lists only support one kind of element, unlike tuples or sets that will allow you to have different types within the same variable – so array data must be reformatted.

“When working with arrays, a common need may arise where one would want to change them into simple lists but maintain their contents in the process. This post discusses how we can easily do so using python language without changing the content.”

Example

input : array('I',[5, 10, 15, 20])

Output : [5, 10, 15, 20]

Program

#importing array class to use array
import array as arr

# an unsigned int type of array 
#declaring and assigning elements to the array
x=arr.array("I",[5, 10, 15, 20])
#performing tolist() operation
x_list=x.tolist()
print(x_list)

Output

[5, 10, 15, 20]

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top