About Lesson
Arrays are data structures that store multiple values of the same type in a single variable. In Python, arrays are used when you need to perform operations on large volumes of data efficiently.
1. What is an Array?
An array is a collection of items stored at contiguous memory locations. All elements in an array must be of the same data type.
In Python, you can use:
list
: A versatile built-in data structure that acts as an array.array
module: Used for type-restricted arrays.NumPy
library: For multidimensional arrays and numerical computations.
2. Why Use Arrays?
- Efficient for storing and accessing large amounts of data.
- Supports element-wise operations.
- Ideal for numerical and scientific computations.
3. Arrays with the array
Module
Importing the Array Module
To use arrays, you must first import the array
module.
import array
Creating an Array
Syntax
array.array(typecode, [elements])
typecode
: Specifies the type of elements in the array.'i'
: Integer'f'
: Float'd'
: Double (larger floating-point numbers)
[elements]
: The list of elements to initialize the array.
Example
import array
# Create an array of integers
numbers = array.array('i', [1, 2, 3, 4, 5])
print(numbers) # Outputs: array('i', [1, 2, 3, 4, 5])
5. Accessing Elements
You can access elements of an array using their index (starting from 0
).
print(numbers[0]) # Outputs: 1
print(numbers[3]) # Outputs: 4
6. Modifying Elements
You can update elements at a specific index.
numbers[1] = 10
print(numbers) # Outputs: array('i', [1, 10, 3, 4, 5])
Adding Elements
append()
: Add a single element to the end of the array.extend()
: Add multiple elements from an iterable.
numbers.append(6) # Adds 6 to the array
print(numbers) # Outputs: array('i', [1, 10, 3, 4, 5, 6])
numbers.extend([7, 8]) # Adds 7 and 8
print(numbers) # Outputs: array('i', [1, 10, 3, 4, 5, 6, 7, 8])
Removing Elements
remove()
: Removes the first occurrence of a value.pop()
: Removes an element by index (default is the last element).
numbers.remove(10) # Removes the first occurrence of 10
print(numbers) # Outputs: array('i', [1, 3, 4, 5, 6, 7, 8])
numbers.pop(2) # Removes the element at index 2
print(numbers) # Outputs: array('i', [1, 3, 5, 6, 7, 8])
Limitations of the array
Module
- Only supports single-dimensional arrays.
- Limited data type support compared to libraries like NumPy.
When to Use NumPy
- If you need to perform mathematical operations on arrays.
- For multidimensional arrays or matrices.
- For better performance in scientific computing.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr + 5) # Adds 5 to each element
Python does not have built-in support for Arrays, but Python Lists can be used instead.