How to create an array in Python
Overview
An array in Python is simply used to store multiple values or item of the same type together.
To create an array in Python we use the array() function after importing the array module. The array() function takes the following parameter values:
data_type: This parameter value specifies which data type of array we want to create. it could be anintegertype,floattype,signed longetc.data_value: This parameter value contains the values of the array you are creating.
It is worthy to note that there are many
data typesand for that reason, some of them are listed in the table below:
| Type code | C type | Python type | Minimum size in bytes |
|---|---|---|---|
'b' |
signed char | int | 1 |
'B' |
unsigned char | int | 1 |
'i' |
signed int | int | 2 |
'I' |
unsigned int | int | 2 |
'f' |
float | float | 4 |
'b' |
double | float | 8 |
Example
Now, let’s create some simple arrays using the array() function.
# importing array from array creationsimport array as arr# to create an array of integer datatype ia = arr.array('i', [1, 2, 3, 4, 5, 6, 7 ])# printing the newly created arrayprint('The integer datatype of array is: ', a)# to create an arry in float datatype db = arr.array('d', [1.2, 2.5, 6.4, 5.1, 4.5])# printing the float arrayprint('The float datatype of array is: ', b)
Explanation
- Line 2: We import the
arraymodule in python. - Line 5: We create an integer type of array variable
a. - Line 8: We print the integer type of array variable,
a, we created in line 5. - Line 12: We create a float type of array variable
b. - Line 15: We print the float type of array variable,
b, which we created in line 12.