Python | Convert an array to an ordinary list with the same items

Published by user on

In this post, we are going to look at the python program to convert an array to an ordinary list with the same items.

Let’s look at sample input and output.

Examples:

Input: array('i' , [50, 100, 150, 200, 250, 300])
Output: [50, 100, 150, 200, 250, 300]
The integer array should be converted to the list.

Input: array('f' , [19.5, 20.8, 56.9, 85.56, 159.85])
Output: [19.5, 20.8, 56.9, 85.56, 159.85]

Let’s look at the programs now.

Convert Array to List in python

We will use the toList() method to do the conversion.

# python program to
# convert array to list
# with same elements
from array import *


array_int = array('i', [10, 20, 30, 40, 50])
# print the values in array
print("Values in array: " + str(array_int))

# here the actual conversion happens
list_int = array_int.tolist()

# print the element in list
print("Elements in list:" + str(list_int))

Output

Values in array: array('i', [10, 20, 30, 40, 50])
Elements in list:[10, 20, 30, 40, 50]

Algorithm
Step 1: Declare and initialize the array with elements
Step 2: Use toList() method to convert the array to list
Step 3: Print the values in list

Categories: python