Course Outline (Part 20)

Note: Python does not have built-in support for native Arrays as a primitive syntax (like C or Java). Python relies on Lists for most array-like behaviors. However, to work with true arrays in Python (where all elements must be of the same type), you must import the array module.

(For multi-dimensional arrays or heavy mathematical operations, data scientists almost exclusively use the NumPy library).


1. Array module

To create a true array, you must import the array module.

import array as arr

2. Create array

When creating an array, you must specify the type code, which determines the C-type of the elements (e.g., 'i' for signed integer, 'd' for double precision float).

import array as arr

# Create an array of integers ('i')
numbers = arr.array('i', [10, 20, 30])
print(numbers) # array('i', [10, 20, 30])

# Create an array of floats ('d')
decimals = arr.array('d', [1.5, 2.5, 3.5])
print(decimals)

3. Access array elements

You access array elements exactly the same way you access list elements: by using the index.

numbers = arr.array('i', [10, 20, 30])

print(numbers[0])  # 10
print(numbers[-1]) # 30 (Negative indexing works too)

# Slicing
print(numbers[1:]) # array('i', [20, 30])

4. Array methods

Arrays share many methods with lists, but since arrays are strictly typed, they are more memory efficient.

  • append(): Adds an element to the end.
  • insert(): Inserts an element at a specific index.
  • pop(): Removes and returns an element.
  • remove(): Removes the first occurrence of a value.
  • extend(): Appends an iterable to the array.
import array as arr

numbers = arr.array('i', [1, 2, 3])

numbers.append(4)
print(numbers) # array('i', [1, 2, 3, 4])

numbers.insert(1, 100)
print(numbers) # array('i', [1, 100, 2, 3, 4])

numbers.remove(100)
print(numbers) # array('i', [1, 2, 3, 4])

5. Loop through array

You can loop through the array elements by using a for loop, just like a list.

import array as arr

numbers = arr.array('i', [10, 20, 30, 40, 50])

for x in numbers:
    print(x)

When to use Arrays vs Lists?

  • Use Lists (the default []) 99% of the time. They are flexible and built-in.
  • Use Arrays (array module) if you need to store a massive amount of numeric data very efficiently in memory, and you do not want the overhead of third-party libraries like NumPy.

Discussion

Loading comments...