Array in Python | Set 2 (Important Functions)
Here are some more functions related.
1. typecode :- This function returns the data type by which array is initialised.
2. itemsize :- This function returns size in bytes of a single array element.
3. buffer_info() :- Returns a tuple representing the address in which array is stored and number of elements in it.
import
array
arr
=
array.array(
'i'
,[
1
,
2
,
3
,
1
,
2
,
5
])
print
(
"The datatype of array is : "
)
print
(arr.typecode)
print
(
"The itemsize of array is : "
)
print
(arr.itemsize)
print
(
"The buffer info. of array is : "
)
print
(arr.buffer_info())
output :
i
The itemsize of array is :
4
The buffer info. of array is :
(1842845731384, 6)
Note -
Instead of import array, we can also use * to import array.
from array import *
arr = array( 'i' ,[ 1 , 2 , 3 , 1 , 2 , 5 ])
print (arr)
output :
array('i', [1, 2, 3, 1, 2, 5]) |
4. count() :- This function counts the number of occurrences of argument mentioned in array.
5. extend(arr) :- This function appends a whole array mentioned in its arguments to the specified array.
import
array
arr1
=
array.array(
'i'
,[
1
,
2
,
3
,
1
,
2
,
5
])
arr2
=
array.array(
'i'
,[
1
,
2
,
3
])
print
(
"The occurrences of 1 in array is : "
)
print
(arr1.count(
1
))
arr1.extend(arr2)
print
(
"The modified array is : "
)
for
i
in
range
(
0
,
9
):
print
(arr1[i])
output :
The occurrences of 1 in array is :
2
The modified array is :
1
2
3
1
2
5
1
2
3
6. fromlist(list) :- This function is used to append a list mentioned in its argument to end of array.
7. tolist() :- This function is used to transform an array into a list.
import
array
arr
=
array.array(
'i'
,[
1
,
2
,
3
,
1
,
2
,
5
])
li
=
[
1
,
2
,
3
]
arr.fromlist(li)
print
(
"The modified array is : "
,end
=
"")
for
i
in
range
(
0
,
9
):
print
(arr[i],end
=
" "
)
li2
=
arr.tolist()
print
(
"\r"
)
print
(
"The new list created is : "
,end
=
"")
for
i
in
range
(
0
,
len
(li2)):
print
(li2[i],end
=
" "
)
output :
The modified array is : 1 2 3 1 2 5 1 2 3
The new list created is : 1 2 3 1 2 5 1 2 3
In this article i have given an introduction on array and functions.
0 Comments
If you have any doubt, Please let me know.