Python Lists vs. Arrays

Python Lists vs. Arrays

In Python, the terms "list" and "array" are often used interchangeably, but they have important distinctions, especially when discussing data structures from a computer science perspective. Understanding this difference is key to writing efficient code.


What is an Array?

In traditional computer science, an Array is a collection of items stored at contiguous memory locations. This means that the items are stored right next to each other in memory, like houses on a street.

Big O Notation: O(1), or "constant time," means the operation takes the same amount of time regardless of the size of the array. It's the fastest possible complexity.


Python's list: The Dynamic Array

Python's built-in list type is not a traditional array. It's a dynamic array. This means it has the fast access of an array but with the flexibility to grow or shrink in size.

When you create a list, Python allocates a certain amount of contiguous memory. If you keep adding items and the allocated space runs out, Python automatically allocates a new, larger block of memory and copies the old elements over.

Python List Example

# A Python list can hold different data types
my_list = [1, "apple", 3.14]
# You can easily add items
my_list.append(True)

Accessing by index is very fast

print(my_list[1]) # Output: apple

print(my_list)

List Time Complexity


Python's array Module

For situations where you need a true, memory-efficient array that stores only items of the same type, Python provides the array module. This is particularly useful for handling large sequences of numbers.

You must specify a "type code" when creating an array to determine the type of its items (e.g., 'i' for signed integer, 'd' for double-precision float).

Using the `array` Module

import array

Create an array of signed integers ('i')

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

print(my_array) print(my_array[2]) # Access is still O(1)

This would cause an error because it's not an integer

my_array.append("hello")

When to use array.array vs. list?


Exercise

?

What is the primary advantage of an array-based structure like Python's list?