📊

Understanding Python Arrays and Their Uses

May 19, 2025

Lecture Notes: Python Arrays

Introduction to Arrays

  • Arrays are similar to lists but require all elements to be of the same type.
  • Unlike lists, arrays cannot have mixed data types; all elements must be integers, floats, or another single type.
  • Arrays are dynamic in size, meaning they can expand or shrink as needed.

Advantages of Arrays

  • Flexibility in size (can add or remove elements).
  • Methods to manipulate arrays, such as append() to add elements and index() to find elements.

When to Use Arrays

  • Useful when dealing with large amounts of data of the same type, such as student grades.

How to Create an Array

  • Import the array module: import array
  • Syntax: array.array(typecode, [elements])
    • typecode specifies the data type of the array.
    • Example: int, float, unicode.

Type Codes and Memory

  • Different type codes determine how much memory each element uses.
    • b for signed integers (1 byte).
    • B for unsigned integers (1 byte).
    • i for regular integers (2 bytes).
    • f for floats (4 bytes).
    • d for double precision floats (8 bytes).
    • u for Unicode characters (2 bytes).

Creating Integer Arrays

  • Example: vals = array.array('i', [5, 9, 8, 4, 2])
  • Arrays must contain only integers if typecode is 'i'.
  • Attempting to add a float will result in an error.

Working with Arrays

  • Arrays support various operations similar to lists.
    • Reverse an Array: vals.reverse()
    • Print Elements: Use loops to iterate through elements.
      • For loop with range(): for i in range(len(vals)): print(vals[i])
      • Enhanced for loop directly on array: for val in vals: print(val)

Creating a New Array

  • Copying an array: new_array = array.array(vals.typecode, (a*a for a in vals))
    • This creates a new array with squared values of the original.

Using While Loops

  • While loops can also iterate over arrays, but require manual management of index and loop controls.
    • Example:
      i = 0
      while i < len(new_array):
        print(new_array[i])
        i += 1
      

Summary

  • Arrays are powerful when dealing with homogeneous data types in Python.
  • The choice between using lists or arrays depends on the requirement of type consistency and memory management.