Skip to main content

Python Arrays

Introduction

Arrays are fundamental data structures in programming that store collections of items of the same data type in contiguous memory locations. While Python doesn't have a built-in array data structure like some other languages, it offers the array module from the standard library that provides an array-like data structure.

In this tutorial, you'll learn:

  • What Python arrays are and how they differ from Python lists
  • How to create and manipulate arrays in Python
  • When to use arrays instead of lists
  • Practical applications of arrays

Python Arrays vs Lists

Before diving into arrays, it's important to understand how they differ from Python's native lists:

FeaturePython ListsPython Arrays
Data typesCan store elements of different typesMust store elements of the same type
Memory efficiencyLess memory efficientMore memory efficient
FlexibilityVery flexibleLess flexible but faster for numerical operations
ImplementationBuilt-in data typeRequires importing the array module

Creating Arrays in Python

To use arrays in Python, you first need to import the array module:

python
import array

When creating an array, you need to specify a type code - a character indicating the type of elements the array will store:

python
# Creating an integer array
import array as arr
integer_array = arr.array('i', [1, 2, 3, 4, 5])
print(integer_array)

Output:

array('i', [1, 2, 3, 4, 5])

Common Type Codes

Here are some common type codes used in Python arrays:

Type CodeC TypePython TypeSize (bytes)
'b'signed charint1
'B'unsigned charint1
'i'signed intint2 or 4
'I'unsigned intint2 or 4
'f'floatfloat4
'd'doublefloat8

Array Operations

Let's explore the basic operations we can perform with Python arrays.

Accessing Elements

Array elements are accessed using indices, just like lists:

python
import array as arr
my_array = arr.array('i', [10, 20, 30, 40, 50])

# Accessing individual elements
print(my_array[0]) # First element
print(my_array[2]) # Third element
print(my_array[-1]) # Last element

Output:

10
30
50

Slicing Arrays

You can slice arrays similarly to lists:

python
import array as arr
my_array = arr.array('i', [10, 20, 30, 40, 50])

# Slicing
print(my_array[1:4]) # Elements from index 1 to 3
print(my_array[::2]) # Every second element

Output:

array('i', [20, 30, 40])
array('i', [10, 30, 50])

Modifying Arrays

Arrays can be modified after creation:

python
import array as arr
my_array = arr.array('i', [10, 20, 30, 40, 50])

# Changing an element
my_array[0] = 15
print(my_array)

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

my_array.extend([70, 80, 90])
print(my_array)

# Inserting an element
my_array.insert(1, 25)
print(my_array)

Output:

array('i', [15, 20, 30, 40, 50])
array('i', [15, 20, 30, 40, 50, 60])
array('i', [15, 20, 30, 40, 50, 60, 70, 80, 90])
array('i', [15, 25, 20, 30, 40, 50, 60, 70, 80, 90])

Removing Elements

Elements can be removed from arrays:

python
import array as arr
my_array = arr.array('i', [10, 20, 30, 40, 50])

# Remove first occurrence of value
my_array.remove(30)
print(my_array)

# Remove element at specific position
popped_element = my_array.pop(1)
print(f"Popped element: {popped_element}")
print(my_array)

Output:

array('i', [10, 20, 40, 50])
Popped element: 20
array('i', [10, 40, 50])

Array Methods

Here are some commonly used array methods:

python
import array as arr
my_array = arr.array('i', [50, 10, 30, 10, 40])

# Count occurrences of a value
print(f"Count of 10: {my_array.count(10)}")

# Get index of first occurrence
print(f"Index of 30: {my_array.index(30)}")

# Reverse the array
my_array.reverse()
print(f"Reversed array: {my_array}")

# Convert array to list
array_list = my_array.tolist()
print(f"Array as list: {array_list}")

Output:

Count of 10: 2
Index of 30: 2
Reversed array: array('i', [40, 10, 30, 10, 50])
Array as list: [40, 10, 30, 10, 50]

When to Use Arrays

Python arrays are particularly useful in the following scenarios:

  1. Memory Efficiency: When dealing with large collections of numerical data, arrays use less memory than lists.
  2. Performance: For mathematical operations on large datasets, arrays can be faster.
  3. Type Consistency: When you need to ensure all elements are of the same type.

However, for most general programming tasks, Python lists are more flexible and convenient. For advanced numerical computations, libraries like NumPy provide more powerful array implementations.

NumPy Arrays: A Brief Introduction

While the standard array module is useful, NumPy arrays are far more powerful for numerical operations:

python
import numpy as np

# Creating a NumPy array
numpy_array = np.array([1, 2, 3, 4, 5])
print(numpy_array)

# Mathematical operations
print(numpy_array * 2) # Multiply each element by 2
print(numpy_array + 5) # Add 5 to each element

Output:

[1 2 3 4 5]
[2 4 6 8 10]
[6 7 8 9 10]

Practical Example: Temperature Readings

Let's solve a real-world problem using arrays. Suppose we have daily temperature readings for a week and want to perform some analysis:

python
import array as arr
import statistics

# Daily temperatures in Celsius for a week
temps = arr.array('f', [22.5, 25.3, 23.1, 19.8, 20.5, 24.6, 22.9])

# Calculate average temperature
avg_temp = sum(temps) / len(temps)
print(f"Average temperature: {avg_temp:.2f}°C")

# Find highest and lowest temperatures
max_temp = max(temps)
min_temp = min(temps)
print(f"Highest temperature: {max_temp}°C")
print(f"Lowest temperature: {min_temp}°C")

# Calculate temperature range
temp_range = max_temp - min_temp
print(f"Temperature range: {temp_range:.2f}°C")

# Calculate standard deviation
std_dev = statistics.stdev(temps)
print(f"Standard deviation: {std_dev:.2f}°C")

Output:

Average temperature: 22.67°C
Highest temperature: 25.3°C
Lowest temperature: 19.8°C
Temperature range: 5.50°C
Standard deviation: 1.91°C

Summary

Python arrays from the array module provide a memory-efficient way to store homogeneous data. While not as commonly used as lists for general programming, they have their place in certain applications where memory efficiency and type consistency are important.

Key points to remember:

  • Arrays require all elements to be of the same type
  • Arrays are more memory-efficient than lists for large collections
  • Arrays have similar operations to lists (indexing, slicing, appending, etc.)
  • For advanced numerical operations, NumPy arrays are more powerful

Additional Resources

Exercises

  1. Create an array of floating-point numbers and calculate their average.
  2. Write a program that reverses an array without using the reverse() method.
  3. Create two arrays and concatenate them into a single array.
  4. Implement a function that removes all occurrences of a specific value from an array.
  5. Compare the memory usage of a Python list vs. an array with 10,000 integers.

By working through these exercises, you'll gain a better understanding of how arrays work in Python and when to use them in your projects.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)