Arrays in Python
An Array in Python is a data structure that stores multiple elements of the same data type in contiguous memory locations.
Arrays are ordered, mutable, and type-restricted, making them more memory-efficient than lists for large numeric data.
In Python, arrays are provided by the built-in array module, which must be imported before use.
Creating an Arrayβ
You create an array using the array() constructor from the array module.
import array
# Empty array of integers
empty_array = array.array('i', [])
# Array of Integers
numbers = array.array('i', [1, 2, 3, 4, 5])
# Array of Floats
floats = array.array('f', [1.1, 2.2, 3.3])
print(numbers) # array('i', [1, 2, 3, 4, 5])
Type Codesβ
Arrays in Python require a type code to specify the element type:
| Type Code | C Type | Python Type | Size (bytes) |
|---|---|---|---|
'i' | signed int | int | 2 or 4 |
'I' | unsigned int | int | 2 or 4 |
'f' | float | float | 4 |
'd' | double | float | 8 |
'b' | signed char | int | 1 |
'B' | unsigned char | int | 1 |
'u' | Py_UNICODE | Unicode | 2 |
Indexingβ
Just like lists, arrays use zero-based indexing.
nums = array.array('i', [10, 20, 30, 40, 50])
print(nums[0]) # 10
print(nums[2]) # 30
print(nums[-1]) # 50
Slicingβ
You can slice arrays to get sub-arrays.
print(nums[1:4]) # array('i', [20, 30, 40])
print(nums[:3]) # array('i', [10, 20, 30])
print(nums[::2]) # array('i', [10, 30, 50])
Syntax:
array[start:stop:step]
Modifying Elementsβ
Arrays are mutable, so you can change elements:
nums[1] = 99
print(nums) # array('i', [10, 99, 30, 40, 50])
Array Methodsβ
Python's array module provides several useful methods:
| Method | Description |
|---|---|
append(x) | Adds an element to the end |
insert(i, x) | Inserts an element at index i |
extend(iterable) | Adds elements from another iterable |
remove(x) | Removes the first occurrence of the item |
pop([i]) | Removes and returns the item at index i |
index(x) | Returns the index of the first occurrence of the item |
count(x) | Counts how many times the item appears |
reverse() | Reverses the array |
buffer_info() | Returns a tuple (memory address, length) |
tobytes() | Converts the array to a bytes object |
frombytes(b) | Appends items from a bytes object |
Examplesβ
append()β
nums = array.array('i', [1, 2, 3])
nums.append(4)
print(nums) # array('i', [1, 2, 3, 4])
insert()β
nums.insert(1, 100)
print(nums) # array('i', [1, 100, 2, 3, 4])
extend()β
nums.extend([5, 6])
print(nums) # array('i', [1, 100, 2, 3, 4, 5, 6])
remove() and pop()β
nums.remove(100)
print(nums) # array('i', [1, 2, 3, 4, 5, 6])
nums.pop() # Removes last element
print(nums) # array('i', [1, 2, 3, 4, 5])
nums.pop(2) # Removes index 2
print(nums) # array('i', [1, 2, 4, 5])
Iterating Through an Arrayβ
Using a for loop:
for num in nums:
print(num)
Using indices:
for i in range(len(nums)):
print(i, nums[i])
Membership Testβ
Check if an element exists in an array:
print(10 in nums) # True or False
print(100 not in nums) # True or False
Array from Listβ
list_data = [1, 2, 3, 4]
arr = array.array('i', list_data)
print(arr)
Copying Arraysβ
Assigning directly creates a reference:
a = array.array('i', [1, 2, 3])
b = a
b.append(4)
print(a) # array('i', [1, 2, 3, 4])
To make an independent copy:
c = array.array(a.typecode, a)
c.append(5)
print(a) # array('i', [1, 2, 3, 4])
print(c) # array('i', [1, 2, 3, 4, 5])
Practice Questionsβ
-
Basic Traversal
Q1: Write a Python program to traverse an array and print each element on a new line.
-
Maximum Element
Q2: Write a Python program to find the maximum and minimum elements in an array without using built-in functions.
-
Array Reversal
Q3: Write a Python program to reverse an array without using slicing or the reverse() method.
-
Insertion Operation
Q4: Write a Python program to insert an element at a specific index in an array.
-
Deletion Operation
Q5: Write a Python program to delete an element from a given index in an array.
-
Search Element
Q6: Write a Python program to search for a given element in an array and print its index if found, otherwise print "Not Found".
-
Sum of Elements
Q7: Write a Python program to find the sum of all elements in an array without using the sum() function.
-
Second Largest Element
Q8: Write a Python program to find the second largest element in an array.
Conclusionβ
Python Arrays are useful when you need to store large amounts of numeric data of the same type efficiently.
They provide faster performance and smaller memory footprint compared to lists for numerical operations.