Home » Python

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

Here, we are going to learn how to convert an array to the list using array.tolist() in Python?
Submitted by IncludeHelp, on September 21, 2018

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()

Example:

  • 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

Program:

# 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]




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.