Arrays and Dynamic Arrays

20 mintext

Theory & Concepts

Arrays and Dynamic Arrays

Arrays are fundamental data structures that store elements in contiguous memory locations.

Key Concepts

1. Static Arrays

  • Fixed size determined at creation
  • Elements stored in contiguous memory
  • Constant time access by index: O(1)
  • Cannot resize after creation

2. Dynamic Arrays

  • Can grow and shrink during runtime
  • Automatically resize when needed
  • Python lists are dynamic arrays
  • Amortized O(1) append operation

Operations and Complexity

| Operation | Static Array | Dynamic Array | |-----------|--------------|---------------| | Access | O(1) | O(1) | | Search | O(n) | O(n) | | Insert | N/A | O(n) | | Delete | N/A | O(n) | | Append | N/A | O(1)* |

*Amortized time complexity

Use Cases

  • Static Arrays: When size is known and fixed
  • Dynamic Arrays: When size varies during execution
  • Lists in Python: General-purpose data storage

Lesson Content

Learn about arrays and dynamic arrays - fundamental data structures for storing collections of elements.

Code Example

python
# Arrays and Dynamic Arrays in Python
# Python lists are dynamic arrays
# Creating arrays (lists)
numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]
mixed = [1, "hello", 3.14, True]
print("Arrays in Python:")
print("Numbers:", numbers)
print("Names:", names)
print("Mixed:", mixed)
# Array operations
print("\nArray Operations:")
# Access by index - O(1)
print("First number:", numbers[0])
print("Last name:", names[-1])
# Length - O(1)
print("Length of numbers:", len(numbers))
# Append - O(1) amortized
numbers.append(6)
print("After append:", numbers)
# Insert - O(n)
numbers.insert(0, 0)
print("After insert at beginning:", numbers)
# Remove - O(n)
numbers.remove(3)
print("After removing 3:", numbers)
# Pop - O(1) for last element, O(n) for others
last = numbers.pop()
print("Popped element:", last)
print("After pop:", numbers)
# Slicing - creates new array
subset = numbers[1:4]
print("Subset [1:4]:", subset)
# Iteration
print("\nIterating through array:")
for i, num in enumerate(numbers):
print(f"Index {i}: {num}")
Section 1 of 1 • Lesson 1 of 1