Python Array fromlist() Method



The Python array fromlist() method is used to append list at the end of an array. When we try to append the list of another datatype we get typeerror.

Syntax

Following is the syntax of the Python array fromlist() method −

array_name.fromlist(list)

Parameters

This method accepts list as a parameter.

Return Value

This method does not return any value.

Example 1

Following is the basic example of the Python array fromlist() method −

import array as arr
#creating an array
my_arr1=arr.array('i',[1,2,3,4,5])
print("Array Before Appending List : ",my_arr1)
#list
list1=[60,70,80,90]
#appending list to the array using method
my_arr1.fromlist(list1)
#printing updated array
print("Array After Appending List : ",my_arr1)

Output

Following is the output of the above code −

Array Before Appending List :  array('i', [1, 2, 3, 4, 5])
Array After Appending List :  array('i', [1, 2, 3, 4, 5, 60, 70, 80, 90])

Example 2

In this method, If the datatype of array and the list are different we get typeerror.

We created an array using the int datatype. However, when we tried to append a list with elements of the float datatype, an error occurred −

import array as arr
my_arr2=arr.array('i',[101,503,209,445,260])
print("Array Before Appending List : ",my_arr2)
list2=[7.3,5.4,6.5]
my_arr2.fromlist(list2)
print("Array After Appending List : ",my_arr2)

Output

Array Before Appending List :  array('i', [101, 503, 209, 445, 260])
Traceback (most recent call last):
  File "/home/cg/root/34104/main.py", line 5, in <module>
    my_arr2.fromlist(list2)
TypeError: 'float' object cannot be interpreted as an integer

Example 3

Lets try to append a list to the empty array of double datatype −

import array as arr
my_arr3=arr.array('d',[])
print("Array Before Appending List : ",my_arr3)
list3=[7.3,5.4,6.5]
my_arr3.fromlist(list3)
print("Array After Appending List : ",my_arr3)

Output

Following is the output of the above code −

Array Before Appending List :  array('d')
Array After Appending List :  array('d', [7.3, 5.4, 6.5])

Example 4

This method only accepts lists as parameters; attempting to append a tuple will result in a TypeError

import array as arr
my_arr4=arr.array('d',[55.6,14.6,48.9,23.6])
print("Array Before Appending List : ",my_arr4)
#appending tuple
list4=(3.5,5.5,1.8)
my_arr4.fromlist(list4)
print("Array After Appending List : ",my_arr4)

Output

Array Before Appending List :  array('d', [55.6, 14.6, 48.9, 23.6])
Traceback (most recent call last):
  File "/home/cg/root/64521/main.py", line 6, in 
    my_arr4.fromlist(list4)
TypeError: arg must be list
python_array_methods.htm
Advertisements