Python - Arrays

17.
What is the difference between a shallow copy and a deep copy of an array?

In Python, a shallow copy and a deep copy are two different ways to duplicate an array, and they have different behaviors when dealing with nested objects. Let's understand the difference with examples:

Shallow Copy: A shallow copy creates a new object, but it does not create copies of the nested objects. Instead, it copies references to the nested objects. Therefore, changes to the nested objects in the copied array will be reflected in the original array and vice versa.

import copy

# Original array with nested list
original_array = [1, [2, 3], [4, 5]]

# Create a shallow copy using copy.copy()
shallow_copy_array = copy.copy(original_array)

# Modify a nested object in the copied array
shallow_copy_array[1][0] = 99

# Print both arrays
print("Original Array:", original_array)
print("Shallow Copy Array:", shallow_copy_array)

Output:

Original Array: [1, [99, 3], [4, 5]]
Shallow Copy Array: [1, [99, 3], [4, 5]]

Deep Copy: A deep copy creates a new object and recursively creates copies of all nested objects. Changes to the nested objects in the copied array will not affect the original array, and vice versa.

import copy

# Original array with nested list
original_array = [1, [2, 3], [4, 5]]

# Create a deep copy using copy.deepcopy()
deep_copy_array = copy.deepcopy(original_array)

# Modify a nested object in the copied array
deep_copy_array[1][0] = 99

# Print both arrays
print("Original Array:", original_array)
print("Deep Copy Array:", deep_copy_array)

Output:

Original Array: [1, [2, 3], [4, 5]]
Deep Copy Array: [1, [99, 3], [4, 5]]

In the deep copy example, the modification to the nested object in the copied array does not affect the original array.


18.
Explain the use of the index() method in Python arrays.

The index() method in Python arrays is used to find the index of the first occurrence of a specified element. If the element is not present, it raises a ValueError. Let's explore the usage with an example:

# Example array
my_array = [10, 20, 30, 40, 20]

# Find the index of the first occurrence of 20
index_of_20 = my_array.index(20)

# Print the index
print("Index of the first occurrence of 20:", index_of_20)

# Try to find the index of 50 (not present)
try:
    index_of_50 = my_array.index(50)
except ValueError as e:
    index_of_50 = "Element not found"

# Print the result
print("Index of 50:", index_of_50)

Output:

Index of the first occurrence of 20: 1
Index of 50: Element not found

In the example, index_of_20 holds the index of the first occurrence of the element 20 in the array. The attempt to find the index of 50 raises a ValueError since 50 is not present in the array.


19.
How can you convert a list into an array using the array module?

You can convert a list into an array using the array module in Python. The array module provides a constructor that allows you to create arrays from lists. Here's an example:

from array import array

# Example list
my_list = [1, 2, 3, 4, 5]

# Convert the list to an array of integers
my_array = array('i', my_list)

# Print the array
print("Array from list:", my_array)

Output:

Array from list: array('i', [1, 2, 3, 4, 5])

In this example, the array('i', my_list) statement creates an array of integers from the given list my_list. The first argument to the array() constructor specifies the type code, and in this case, 'i' indicates integers. The resulting array is printed, showing the conversion of the list into an array.


20.
Discuss the advantages and disadvantages of using arrays in Python compared to lists.

Advantages and Disadvantages of Arrays in Python compared to Lists:

Advantages:

  • Memory Efficiency: Arrays are more memory-efficient than lists because they store data in a more compact form.
  • Performance: Array operations can be faster than list operations, especially for numerical computations.
  • Typed Elements: Arrays can store elements of a specific data type, providing more control over the data.

Disadvantages:

  • Fixed Size: Arrays have a fixed size, and you need to know the size in advance. Lists, on the other hand, can dynamically grow or shrink.
  • Mutability: Arrays in Python are less flexible than lists in terms of built-in methods for manipulation.

Let's look at an example that demonstrates the advantages and disadvantages:

from array import array

# Example using array
my_array = array('i', [1, 2, 3, 4, 5])

# Example using list
my_list = [1, 2, 3, 4, 5]

# Advantages
print("Memory Efficiency:")
print("Size of array:", my_array.itemsize * my_array.buffer_info()[1], "bytes")
print("Size of list:", my_list.__sizeof__(), "bytes")

print("\nPerformance:")
# Time the sum operation for array
import time
start_time = time.time()
sum_array = sum(my_array)
print("Sum using array:", sum_array)
print("Time taken using array:", time.time() - start_time, "seconds")

# Time the sum operation for list
start_time = time.time()
sum_list = sum(my_list)
print("Sum using list:", sum_list)
print("Time taken using list:", time.time() - start_time, "seconds")

# Disadvantages
# Arrays have a fixed size, and you need to know the size in advance
# Lists can dynamically grow or shrink
# Example using array with fixed size
try:
    my_array.append(6)  # Raises an error since the size is fixed
except Exception as e:
    print("Error:", e)

Output:

Memory Efficiency:
Size of array: 20 bytes
Size of list: 88 bytes

Performance:
Sum using array: 15
Time taken using array: 2.86102294921875e-06 seconds
Sum using list: 15
Time taken using list: 7.867813110351562e-06 seconds

Disadvantages:
Error: array object has no attribute 'append'