Python - Arrays

13.
What is the purpose of the reverse() method for arrays?

The reverse() method in Python arrays is used to reverse the order of elements in the array. Here's an example:

# Create an array
my_array = [1, 2, 3, 4, 5]

# Use the reverse() method to reverse the array
my_array.reverse()

print("Reversed Array:", my_array)

Output:

Reversed Array: [5, 4, 3, 2, 1]

In the example, the reverse() method is called on the array my_array, which contains the elements 1 through 5. After the reversal, the array elements are printed in the reversed order.


14.
How do you iterate over elements in an array using a for loop?

Iterating over elements in a Python array using a for loop is a common practice. Here's an example:

# Create an array
my_array = [1, 2, 3, 4, 5]

# Iterate over elements using a for loop
for element in my_array:
    print(element)

Output:

1
2
3
4
5

In this example, the for loop iterates over each element in the array my_array, and the print() statement prints each element on a new line. This is a simple way to access and process each element in the array.


15.
Discuss the use of the pop() method in Python arrays.

The pop() method in Python arrays is used to remove and return the element at a specified index. Here's an example:


# Create an array
my_array = [10, 20, 30, 40, 50]

# Use pop() to remove and return the element at index 2
removed_element = my_array.pop(2)

# Print the modified array and the removed element
print("Modified Array:", my_array)
print("Removed Element:", removed_element)

Output:

Modified Array: [10, 20, 40, 50]
Removed Element: 30

In this example, the pop(2) method removes the element at index 2 (which is 30) from the array my_array and returns the removed element. The modified array and the removed element are then printed.


16.
How can you sort the elements of an array in ascending and descending order?

To sort the elements of an array in Python, you can use the sorted() function for ascending order and the reverse parameter for descending order. Here's an example:

# Create an array
my_array = [40, 10, 30, 20, 50]

# Sort the array in ascending order using sorted()
ascending_order = sorted(my_array)

# Sort the array in descending order using sorted() with reverse parameter
descending_order = sorted(my_array, reverse=True)

# Print the original, ascending, and descending order arrays
print("Original Array:", my_array)
print("Ascending Order:", ascending_order)
print("Descending Order:", descending_order)

Output:

Original Array: [40, 10, 30, 20, 50]
Ascending Order: [10, 20, 30, 40, 50]
Descending Order: [50, 40, 30, 20, 10]

In this example, the sorted() function is used to create new arrays in ascending and descending order from the original array my_array. The original, ascending, and descending order arrays are then printed.