Array Operations
In this section, we will explore various operations that can be performed on arrays. These operations are essential for efficiently storing and manipulating data.
Accessing Elements
Arrays in Python are 0-indexed, which means the first element is at index 0. You can access elements in an array using their index. For example:
1# Create an array
2array = [1, 2, 3, 4, 5]
3
4# Accessing elements in an array
5print(array[0]) # Output: 1
Modifying Elements
You can modify elements in an array by assigning a new value to a specific index. For example:
1# Modifying elements in an array
2array[2] = 6
3print(array) # Output: [1, 2, 6, 4, 5]
Finding the Length
To find the length of an array, you can use the len()
function. It returns the number of elements in the array. For example:
1# Finding the length of an array
2print(len(array)) # Output: 5
Adding Elements
Adding elements to an array can be done using the append()
method. It adds the element to the end of the array. For example:
1# Adding elements to an array
2array.append(7)
3print(array) # Output: [1, 2, 6, 4, 5, 7]
Removing Elements
To remove an element from an array, you can use the pop()
method and provide the index of the element. It removes and returns the element at the specified index. For example:
1# Removing elements from an array
2array.pop(3)
3print(array) # Output: [1, 2, 6, 5, 7]
Searching for an Element
To search for an element in an array, you can implement a linear search algorithm. Here's an example:
1# Searching for an element in an array
2
3def search_element(arr, target):
4 for i in range(len(arr)):
5 if arr[i] == target:
6 return i
7 return -1
8
9print(search_element(array, 6)) # Output: 2
10print(search_element(array, 8)) # Output: -1
Sorting an Array
To sort an array in ascending order, you can use the sort()
method. For example:
1# Sorting an array
2array.sort()
3print(array) # Output: [1, 2, 5, 6, 7]
Reversing an Array
To reverse the order of elements in an array, you can use the reverse()
method. For example:
1# Reversing an array
2array.reverse()
3print(array) # Output: [7, 6, 5, 2, 1]
xxxxxxxxxx
print(array) # Output: [7, 6, 5, 2, 1]
# Python logic here
# Create an array
array = [1, 2, 3, 4, 5]
# Accessing elements in an array
print(array[0]) # Output: 1
# Modifying elements in an array
array[2] = 6
print(array) # Output: [1, 2, 6, 4, 5]
# Finding the length of an array
print(len(array)) # Output: 5
# Adding elements to an array
array.append(7)
print(array) # Output: [1, 2, 6, 4, 5, 7]
# Removing elements from an array
array.pop(3)
print(array) # Output: [1, 2, 6, 5, 7]
# Searching for an element in an array
def search_element(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1