Data Structures Explained with Python

Arrays and Lists in Python

Arrays

An array is a fundamental data structure that stores a collection of elements of the same data type in contiguous memory locations. This contiguity allows for efficient random access to elements using their index (position).

Characteristics of Arrays:

In Python, the array module can be used to create arrays of a specific type. However, Python'''s built-in lists are more commonly used and are more flexible.


# Python'''s array module
import array

# Create an array of integers
int_array = array.array('''i''', [10, 20, 30, 40, 50])
print(f"Integer Array: {int_array}")
print(f"Element at index 2: {int_array[2]}")

# Create an array of floating-point numbers
float_array = array.array('''d''', [1.5, 2.5, 3.5])
print(f"Float Array: {float_array}")
        

Lists in Python

Python'''s lists are more versatile than traditional arrays. They are dynamic, meaning their size can change, and they can store elements of different data types (heterogeneous).

Characteristics of Python Lists:

Creating Lists:


# Empty list
my_list = []
print(f"Empty list: {my_list}")

# List of integers
numbers = [1, 2, 3, 4, 5]
print(f"List of numbers: {numbers}")

# List with mixed data types
mixed_list = [1, "Hello", 3.14, True]
print(f"Mixed list: {mixed_list}")

# Nested list (list of lists)
nested_list = [[1, 2], [3, 4]]
print(f"Nested list: {nested_list}")
        

Common List Operations:


# List operations examples
numbers = [10, 20, 30, 40, 50]

# Accessing
print(f"First element: {numbers[0]}") # Output: 10
print(f"Last element: {numbers[-1]}") # Output: 50

# Slicing
print(f"Slice [1:3]: {numbers[1:3]}") # Output: [20, 30]

# Appending
numbers.append(60)
print(f"After append(60): {numbers}") # Output: [10, 20, 30, 40, 50, 60]

# Inserting
numbers.insert(1, 15) # Insert 15 at index 1
print(f"After insert(1, 15): {numbers}") # Output: [10, 15, 20, 30, 40, 50, 60]

# Removing
numbers.remove(30) # Removes the value 30
print(f"After remove(30): {numbers}") # Output: [10, 15, 20, 40, 50, 60]

# Popping
popped_element = numbers.pop(2) # Removes and returns element at index 2
print(f"Popped element: {popped_element}") # Output: 20
print(f"After pop(2): {numbers}") # Output: [10, 15, 40, 50, 60]

# Length
print(f"Length of list: {len(numbers)}") # Output: 5
        

When to Use Arrays vs. Lists:

In Python, lists are generally the go-to for ordered collections due to their flexibility. However:

Understanding arrays and lists is crucial as they form the basis for many other complex data structures and algorithms.