Python - Create an Integer Array
Create an Integer Array in Python
In Python, you can create an integer array using array() method of array module.
In this tutorial, you will learn how to create a Python array with integer values in it, with examples.
To create an integer array in Python, import array module, call array() method of array module, and pass the type code for integer type as first argument and the list of elements for the initial values of array as second argument.
array(type_code, initial_values)
You can use any of the following type code to create an integer array.
Type Code | C data type | Python data type | Minimum number of bytes |
---|---|---|---|
'b' | signed char | int | 1 |
'B' | unsigned char | int | 1 |
'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 |
Initial values (second argument) to the array()
method is optional. If you do not pass any initial values, then an empty integer array would be created.
1. Create an integer array with initial values
In the following program, we create an integer array my_array using array() method. Pass 'i'
type code as first argument to the array() method, and pass a list of initial values to the array as second argument to the array() method.
Python Program
import array as arr
my_array = arr.array('i', [100, 200, 300, 400])
print(my_array)
Output
array('i', [100, 200, 300, 400])
2. Create an empty integer array and add values
We can also create an empty integer array, and then append values to the array.
In the following program, we create an empty integer array my_array, and then add some integer elements to this array.
Python Program
import array as arr
my_array = arr.array('i')
my_array.append(100)
my_array.append(200)
my_array.append(300)
my_array.append(400)
print(my_array)
Output
array('i', [100, 200, 300, 400])
3. Iterate over Integer Array
We can use a For loop to iterate over the elements of given integer array.
In the following program, we take an integer array my_array, and then use a For loop to iterate over the integer elements in the array.
Python Program
import array as arr
my_array = arr.array('i', [100, 200, 300, 400])
for element in my_array:
print(element)
Output
100
200
300
400
Summary
In this Python Array tutorial, we learned how to create an integer array in Python, using array() method of array module, with examples.