Python Arrays

Mastering Arrays in Python

🎯 Understanding Python Arrays

Arrays in Python are ordered collections that can store multiple items in a single variable. Python offers several ways to work with array-like structures.


# Different ways to create arrays in Python
my_list = [1, 2, 3, 4, 5]           # Using List
from array import array
my_array = array('i', [1, 2, 3])    # Using array module
import numpy as np
np_array = np.array([1, 2, 3])      # Using NumPy
                                    
3+
Array Types
O(1)
Access Time
Dynamic
Size Growth

Python Lists as "Arrays"

For most common programming tasks, Python's built-in Lists are sufficient and behave like dynamic arrays.

Basic List Operations
# Creating a list
my_list = ["apple", "banana", "cherry"]
print(my_list)

# Accessing elements
print(my_list[0]) # Output: apple

# Modifying elements
my_list[1] = "orange"
print(my_list) # Output: ['apple', 'orange', 'cherry']

# Adding elements
my_list.append("grape")
print(my_list) # Output: ['apple', 'orange', 'cherry', 'grape']

# Removing elements
my_list.remove("apple")
print(my_list) # Output: ['orange', 'cherry', 'grape']

The Python array Module

If you need to work with arrays of a specific data type and want to save memory, Python's built-in array module is a good choice. It's more efficient than lists for storing large sequences of numbers.

📊 Common Type Codes:

  • 'i' : signed integer (2 bytes)
  • 'f' : floating point (4 bytes)
  • 'd' : double precision floating point (8 bytes)
Array Module Example
from array import array

# Create an array of signed integers
my_array = array('i', [1, 2, 3, 4, 5])
print(my_array)

# Accessing elements
print(my_array[0])

# Modifying elements
my_array[1] = 10
print(my_array)

# Adding elements
my_array.append(6)
print(my_array)

# Removing elements
my_array.remove(3)
print(my_array)

NumPy Arrays (for Data Science)

For advanced numerical operations, especially in data science and machine learning, the NumPy library is the standard. NumPy arrays (ndarray) are highly optimized for performance and provide powerful mathematical functions.

NumPy Array Example
import numpy as np

# Create a NumPy array
np_array = np.array([1, 2, 3, 4, 5])
print(np_array)
print(type(np_array))

# Perform element-wise operations
print(np_array * 2)

# Create a 2D array (matrix)
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)

# Accessing elements in 2D array
print(matrix[0, 1]) # Output: 2 (row 0, column 1)