What is an Array Introduction
An array is a data structure that stores multiple items of the same data type. Unlike Python’s built-in lists, which can store different data types, arrays are designed for homogenous data storage (e.g., only integers or floats). This feature makes arrays more efficient in memory and computation, especially for numerical data. In Python, arrays store multiple values in a single variable(my_list). While Python does not have a built-in array data type like some other programming languages, arrays can be implemented using the following:
- Lists (basic built-in type)
- array module (supports type-specific arrays)
- NumPy library (for scientific computing)
Using Lists
Python’s built-in lists are a versatile way to store arrays, as they can hold items of any data type.
# Creating an array using a list
my_list = [1, 2, 3, 4, 5]
# Accessing elements
print(my_list[0]) # Output: 1
# Modifying elements
my_list[1] = 10
print(my_list) # Output: [1, 10, 3, 4, 5]
# Adding an element
my_list.append(6)
print(my_list) # Output: [1, 10, 3, 4, 5, 6]
2. Using the Array Module
The array module provides arrays with more structure. It enforces that all elements are of the same type (e.g., integers, floats).
import array
# Creating an integer array
my_array = array.array(‘i’, [1, 2, 3, 4, 5])
# Accessing elements
print(my_array[0]) # Output: 1
# Modifying elements
my_array[1] = 10
print(my_array) # Output: array(‘i’, [1, 10, 3, 4, 5])
# Adding an element
my_array.append(6)
print(my_array) # Output: array(‘i’, [1, 10, 3, 4, 5, 6])
3. Using NumPy Arrays
The NumPy library is highly efficient for working with large arrays and performing mathematical operations.
Install NumPy if you haven’t already:
pip install numpy
import numpy as np
# Creating a NumPy array
my_numpy_array = np.array([1, 2, 3, 4, 5])
# Accessing elements
print(my_numpy_array[0]) # Output: 1
# Modifying elements
my_numpy_array[1] = 10
print(my_numpy_array)
# Adding an element
my_numpy_array = np.append(my_numpy_array, 6)
print(my_numpy_array)
Characteristics of Array
Python provides several ways to work with arrays. The most common methods are through the array module (for low-level arrays) and list (Python’s built-in data structure, which functions similarly to arrays in other languages). For true arrays with fixed types, you can also use NumPy arrays. Below are the characteristics of arrays in Python, focusing on the array module arrays.
- Homogeneous Elements
- Arrays created using Python’s array module are homogeneous(same data type), meaning that all elements in the array must be of the same data type.
- You must specify a type code when creating an array (e.g., ‘i’ for integers, ‘f’ for floating-point numbers).
Syntax:
import array
# Creating an array of integers
int_array = array.array(‘i’, [1, 2, 3, 4, 5])
# Creating an array of floats
float_array = array.array(‘f’, [1.1, 2.2, 3.3])
- Efficient Memory Usage
- Arrays use contiguous memory allocation, which means they are more memory-efficient compared to Python lists, especially when dealing with large amounts of numerical data.
- Unlike lists, arrays store data more compactly because they enforce a fixed type for all elements.
Syntax:
import sys
# Comparing memory usage between a list and an array
my_list = [1, 2, 3, 4, 5]
my_array = array.array(‘i’, [1, 2, 3, 4, 5])
print(sys.getsizeof(my_list)) # More memory (due to dynamic typing)
print(sys.getsizeof(my_array)) # Less memory (fixed-type array)
- Fixed Data Type
- Arrays in the array module enforce a fixed data type for all its elements, which is specified by the type code.
- You cannot store elements of different data types(heterogeneous) in a single array. This differs from Python lists(mixed = [1, “apple”, 3.14, True]), which allow mixed data types.
Syntax:
# This will raise an error because of the incompatible data type
try:
int_array = array.array(‘i’, [1, 2, ‘three’]) # Mixing integer with string
except TypeError as e:
print(e) # Output: an integer is required
- Supports Various Numeric Data Types
- Arrays in Python support several numeric data types, specified by type codes. Some of the common type codes are:
- ‘i’: Signed integers (2 or 4 bytes, depending on the platform)
- ‘I’: Unsigned integers (2 or 4 bytes)
- ‘f’: Floating-point numbers (4 bytes)
- ‘d’: Double-precision floats (8 bytes)
- ‘b’: Signed char (1 byte)
- ‘B’: Unsigned char (1 byte)
# Creating an array of unsigned integers
unsigned_int_array = array.array(‘I’, [100, 200, 300])
- Indexed Access and Slicing
- Arrays support indexed access and slicing, allowing you to retrieve, modify, or manipulate elements just like in Python lists.
- Negative indexing(print(int_array[-1]) ) is also supported, allowing you to access elements from the end of the array.
# Accessing elements by index
print(int_array[0]) # Output: 1
print(int_array[-1]) # Output: 5 (last element)
# Slicing the array
print(int_array[1:4]) # Output: array(‘i’, [2, 3, 4])
- Mutable
- Arrays in Python are mutable, meaning that you can modify the values of elements after the array has been created.
- You can also use methods like append(), insert(), and remove() to modify the contents of the array.
# Modifying elements
int_array[0] = 10
print(int_array) # Output: array(‘i’, [10, 2, 3, 4, 5])
# Appending an element
int_array.append(6)
print(int_array) # Output: array(‘i’, [10, 2, 3, 4, 5, 6])
# Removing an element
int_array.remove(3)
print(int_array) # Output: array(‘i’, [10, 2, 4, 5, 6])
- Dynamic Resizing
- Although arrays in Python are more memory-efficient than lists, they can still resize dynamically. You can add or remove elements without worrying about pre-allocating memory, although the resizing process may not be as fast as with lists.
# Appending elements dynamically
int_array.append(7)
print(int_array) # Output: array(‘i’, [10, 2, 4, 5, 6, 7])
- Supports Basic Operations
- Python arrays support basic operations such as iteration, concatenation, and multiplication.
# Iterating over an array
for num in int_array:
print(num)
# Concatenating two arrays
array1 = array.array(‘i’, [1, 2, 3])
array2 = array.array(‘i’, [4, 5, 6])
result = array1 + array2
print(result) # Output: array(‘i’, [1, 2, 3, 4, 5, 6])
# Multiplying an array
print(array1 * 2) # Output: array(‘i’, [1, 2, 3, 1, 2, 3])
What is PYTHON?