Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python Array fromlist() Method



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

Syntax

Following is the syntax of the Python arrayfromlist() 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 arrayfromlist() method −

import array as arr#creating an arraymy_arr1=arr.array('i',[1,2,3,4,5])print("Array Before Appending List : ",my_arr1)#listlist1=[60,70,80,90]#appending list to the array using methodmy_arr1.fromlist(list1)#printing updated arrayprint("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 gettypeerror.

We created an array using theint datatype. However, when we tried to append a list with elements of thefloat datatype, anerror occurred −

import array as arrmy_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 ofdouble datatype −

import array as arrmy_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 aTypeError

import array as arrmy_arr4=arr.array('d',[55.6,14.6,48.9,23.6])print("Array Before Appending List : ",my_arr4)#appending tuplelist4=(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
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp