Array Manipulation
Array manipulation involves various methods for adding, removing, and modifying elements in an array. These methods allow us to dynamically update the contents of an array based on our specific needs.
Adding Elements to an Array
To add elements to an array in Python, we can use the append()
method. This method appends the specified element to the end of the array.
Here's an example:
1# Creating an empty array
2arr = []
3
4# Adding elements to the array
5arr.append(1)
6arr.append(2)
7arr.append(3)
8
9print(arr) # Output: [1, 2, 3]
In this example, we create an empty array arr
and then add elements 1
, 2
, and 3
to the array using the append()
method. Finally, we print the updated array, which will output [1, 2, 3]
.
Removing Elements from an Array
To remove elements from an array in Python, we have multiple options. One common method is to use the remove()
method, which removes the first occurrence of the specified element from the array.
Here's an example:
1# Removing an element by value
2arr.remove(2)
3
4print(arr) # Output: [1, 3]
In this example, we remove the element 2
from the array arr
using the remove()
method. After removing the element, the array will contain [1, 3]
.
Modifying Elements in an Array
To modify elements in an array, we can simply assign a new value to the desired index in the array.
Here's an example:
1# Modifying an element at a specific index
2arr[1] = 4
3
4print(arr) # Output: [1, 4]
In this example, we modify the element at index 1
in the array arr
by assigning a new value 4
to it. After the modification, the array will be [1, 4]
.
Array manipulation methods like adding, removing, and modifying elements allow us to update the content of an array dynamically. These methods are essential for working with arrays in various programming scenarios, including robotics and computer vision applications.
xxxxxxxxxx
# Example 1: Adding Elements to an Array
# Creating an empty array
arr = []
# Adding elements to the array
arr.append(1)
arr.append(2)
arr.append(3)
print(arr) # Output: [1, 2, 3]
# Example 2: Removing Elements from an Array
# Removing an element by value
arr.remove(2)
print(arr) # Output: [1, 3]
# Example 3: Modifying Elements in an Array
# Modifying an element at a specific index
arr[1] = 4
print(arr) # Output: [1, 4]