How to use Array in Python

An array is a collection of similar type items stored at contiguous memory locations.
In Python, array can be handled using the module array
. Arrays are useful when we have to manipulate only a specific data type values. A user can treat lists as array, but the difference is that a list contain elements of different data types whereas in array this is not possible.
In the array module, the function array(data_type, value_list)
can be used to create array.
Use the below table to correctly assign value to data_type
Datatype Code | C type | Python Type | Minimum Size in Bytes |
‘b’ | signed char | int | 1 |
‘B’ | unsigned char | int | 1 |
‘u’ | Py_UNICODE | unicode character | 2 |
‘h’ | signed short | int | 2 |
‘H’ | unsigned short | int | 2 |
‘i’ | signed int | int | 2 |
‘I’ | unsigned int | int | 2 |
‘l’ | signed long | int | 4 |
‘L’ | unsigned long | int | 4 |
‘q’ | signed long long | int | 8 |
‘Q’ | unsigned long long | int | 8 |
‘f’ | float | float | 4 |
‘d’ | double | float | 8 |
import array #creating an array with integer type a = array.array('i', [1, 3, 5, 7, 9]) for i in range(len(a)): print(a[i], end=" ") print() #creating an array with float type: arr = array.array('d',[1.2, 2.4, 4.8]) for i in range(len(arr)): print(arr[i], end=" ")
Output:
1 3 5 7 9 1.2 2.4 4.8
Subscribe
Login
Please login to comment
0 Discussion