Python Array – 13 Examples

Python doesn’t have explicit array data structure. It’s because we can do the same things with the List.

The list contains a collection of items and it supports add/update/delete/search operations. That’s why there is not much use of a separate data structure in Python to support arrays.

An array contains items of the same type but Python list allows elements of different types. This is the only feature wise difference between an array and a list. But it’s not a deal breaker and doesn’t warrant a new data structure support in Python.

However, Python array module can be used to create an array like object for integer, float, and Unicode characters.


Python array Module

Python array module allows us to create an array with constraint on the data types. There are only a few data types supported by this module.

Python Array Supported Type Code
Python Array Supported Type Code

The Unicode type code has been deprecated in Python 3.3 and it will be removed in Python 4.0 release.

So, we can create an array of integers and float using array module. Let’s get started with the array module and look at all the operations it provides.


1. Creating an Array

The syntax to create an array is array.array(typecode, values_list).

import array

# creating array
int_array = array.array('i', [1, 2, 3, 4])

float_array = array.array('f', [1.1, 2.2, 3.3, 4.4])

# unicode array support is deprecated and will be deleted in Python 4
unicode_array = array.array('u', ['\u0394', '\u2167', '\u007B'])

2. Printing Array and its Type

If we print the array object, it gives us information about the typecode and its elements. Let’s print the arrays created above and also print the object type using the type() built-in function.

# printing array
print(int_array)
print(float_array)
print(unicode_array)
print(type(int_array))

Output:

array('i', [1, 2, 3, 4])
array('f', [1.100000023841858, 2.200000047683716, 3.299999952316284, 4.400000095367432])
array('u', 'ΔⅧ{')
<class 'array.array'>

3. Printing Array Elements

We can print array elements using the for loop.

import array

int_array = array.array('i', [1, 2, 3, 4])

for a in int_array:
    print(a)

We can also access an element using its index. We can use the indices to print the array elements.

for b in range(0, len(int_array)):
    print(f'int_array[{b}] = {int_array[b]}')

Output:

int_array[0] = 1
int_array[1] = 2
int_array[2] = 3
int_array[3] = 4

4. Inserting and Appending Elements

We can use the insert() function to insert an element at the specified index. The elements from the specified index are shifted to right by one position.

int_array = array.array('i', [1, 2, 3, 4])
int_array.insert(0, -1)  # -1,1,2,3,4
int_array.insert(2, -2)  # -1,1,-2,2,3,4
print(int_array)

Output: array('i', [-1, 1, -2, 2, 3, 4])

If you have to add an element at the end of the array, use append() function.

int_array = array.array('i', [1, 2, 3, 4])
int_array.append(-3)
print(int_array)  # array('i', [1, 2, 3, 4, -3])

5. Python array supports negative index

We can access python array elements through negative index too.

Python Array Index
Python Array Index
int_array = array.array('i', [10, 20, 30, 40, 50, 60, 70, 80])
print(int_array[-2])  # 70
print(int_array[-5])  # 40

6. Removing Array Elements

We can use remove() method to remove an array element.

int_array = array.array('i', [1, 2, 3, 4])
int_array.remove(2)
print(int_array)  # array('i', [1, 3, 4])

If the element is not present in the array, ValueError is raised.

int_array = array.array('i', [1, 2, 3, 4])
try:
    int_array.remove(20)
except ValueError as ve:
    print(ve)

Output: array.remove(x): x not in array

We can also use pop() function to remove an element at the given index. This function returns the element being removed from the array. If we don’t specify the index, the last element is removed and returned.

int_array = array.array('i', [1, 2, 3, 4])
last_element = int_array.pop()
print(last_element)  # 4
print(int_array)  # array('i', [1, 2, 3])

second_element = int_array.pop(1)
print(second_element)  # 2
print(int_array)  # array('i', [1, 3])

7. Slicing an Array

Python array supports slicing and returns a new array with the sub-elements. The original array remains unchanged. The slicing also supports negative indices.

int_array = array.array('i', [0, 1, 2, 3, 4, 5])
print(int_array[3:])  # array('i', [3, 4, 5])
print(int_array[:2])  # array('i', [0, 1])
print(int_array[1:3])  # array('i', [1, 2])

# negative index slicing
print(int_array[-2:])  # array('i', [4, 5])
print(int_array[:-2])  # array('i', [0, 1, 2, 3])

8. Searching an Element in the Array

We can use the index() function to find the index of first occurrence of an element. If the element is not present in the array, ValueError is raised.

int_array = array.array('i', [0, 1, 2, 3, 1, 2])

print(f'1 is found at index {int_array.index(1)}')
try:
    print(int_array.index(20))
except ValueError as ve:
    print(ve)

Output:

1 is found at index 1
array.index(x): x not in array

9. Updating Value at Specified Index

We can use the array index with the assignment operator to update the value at an index. If the index is invalid, IndexError is raised.

int_array = array.array('i', [0, 1, 2, 3, 1, 2])

int_array[0] = -1
int_array[1] = -2
print(int_array)

try:
    int_array[10] = -10
except IndexError as ie:
    print(ie)

Output:

array('i', [-1, -2, 2, 3, 1, 2])
array assignment index out of range

10. Reversing an Array

We can use the reverse() function to reverse the array elements.

int_array = array.array('i', [0, 1, 2, 3])
int_array.reverse()
print(int_array)  # array('i', [3, 2, 1, 0])

11. Count of the Occurrence of an Element

We can use the count() function to get the number of occurrences of a value in the array.

int_array = array.array('i', [0, 1, 1, 0])
print(int_array.count(1))  # 2
print(int_array.count(10))  # 0

12. Extending an Array by Appending an Iterable

We can use the extend() function to append values from the iterable to the end of the array.

array1 = array.array('i', [0, 1])
array2 = array.array('i', [2, 3, 4])

array1.extend(array2)
print(array1)  # array('i', [0, 1, 2, 3, 4])

print(array2)  # array('i', [2, 3, 4])
array2.extend([1, 2])
print(array2)  # array('i', [2, 3, 4, 1, 2])

array1 = array.array('i', [1])
array1.extend(set([0,0,0,2]))
print(array1)  # array('i', [1, 0, 2])

13. Converting Array to List

We can use the tolist() function to convert an array to a list.

int_array = array.array('i', [0, 1, 2, 3])
print(int_array.tolist())  # [0, 1, 2, 3]

Conclusion

Python array module helps us in creating arrays for integers and float. But, we can perform the same operations with a list. So you should use the array module only when you want the data to be constrained to the given type.


References: