Array Operations
In this tutorial, you will learn how to perform operations on arrays. how to perform loop, copy, reverse, sort, search, and join operations on arrays.
Looping Array Elements
You can access the array elements by using the loop statement.
For Loop
The for loop is used to iterate over the array elements. The for loop is used to iterate over the array elements.
import array as arr
my_array = arr.array('i', [1, 2, 3, 4, 5])
for i in my_array:
print(i)Output:
C:\Users\username>python array_for_loop.py
1
2
3
4
5In the above example, we create an array of five elements and iterate over the array elements using the for loop.
While Loop
The while loop is used to iterate over the array elements until the given condition is true.
import array as arr
my_array = arr.array('i', [1, 2, 3, 4, 5])
i = 0
while i < len(my_array):
print(my_array[i])
i += 1Output:
C:\Users\username>python array_while_loop.py
1
2
3
4
5In the above example, we create an array of five elements and iterate over the array elements using the while loop.
Using Range() Function
The range() function returns a sequence of numbers starting from zero to the specified number minus one.
import array as arr
my_array = arr.array('i', [1, 2, 3, 4, 5])
for i in range(len(my_array)):
print(my_array[i])Output:
C:\Users\username>python array_range.py
1
2
3
4
5In the above example, we create an array of five elements and iterate over the array elements using the range() function.
Copying Array
You can copy the array elements to another array using the copy() method and deepcopy() function.
= operator
The = operator is used to copy the array elements to another array.
import array as arr
my_array = arr.array('i', [1, 2, 3, 4, 5])
new_array = my_array
print("Before updating")
print(my_array)
print(new_array)
new_array[0] = 6
print("After updating")
print(my_array)
print(new_array)Output:
C:\Users\username>python array_copy.py
Before updating
array('i', [1, 2, 3, 4, 5])
array('i', [1, 2, 3, 4, 5])
After updating
array('i', [6, 2, 3, 4, 5])
array('i', [6, 2, 3, 4, 5])In the above example, we create an array of five elements and copy the array elements to another array using the = operator. After updating, we change the first element of the new array. The first element of the original array is also changed.
copy() method
The copy() method returns a shallow copy of the array.
import array as arr
my_array = arr.array('i', [1, 2, 3, 4, 5])
new_array = my_array.copy()
print("Before updating")
print(my_array)
print(new_array)
new_array[0] = 6
print("After updating")
print(my_array)
print(new_array)Output:
C:\Users\username>python array_copy.py
Before updating
array('i', [1, 2, 3, 4, 5])
array('i', [1, 2, 3, 4, 5])
After updating
array('i', [1, 2, 3, 4, 5])
array('i', [6, 2, 3, 4, 5])In the above example, we create an array of five elements and copy the array elements to another array using the copy() method. After updating, we change the first element of the new array. The first element of the original array is not changed.
deepcopy() function
The deepcopy() function returns a deep copy of the array.
import array as arr
import copy
my_array = arr.array('i', [1, 2, 3, 4, 5])
new_array = copy.deepcopy(my_array)
print("Before updating")
print(my_array)
print(new_array)
new_array[0] = 6
print("After updating")
print(my_array)
print(new_array)Output:
C:\Users\username>python array_deepcopy.py
Before updating
array('i', [1, 2, 3, 4, 5])
array('i', [1, 2, 3, 4, 5])
After updating
array('i', [1, 2, 3, 4, 5])
array('i', [6, 2, 3, 4, 5])In the above example, we create an array of five elements and copy the array elements to another array using the deepcopy() function. After updating, we change the first element of the new array. The first element of the original array is not changed.
Reversing Array
Reverse the order of the items in the array using the reverse() method and negative indexing.
Negative Indexing
Negative indexing is used to access the array elements from the end of the array.
import array as arr
my_array = arr.array('i', [1, 2, 3, 4, 5])
reverse_array = my_array[::-1]
print("Original array")
print(my_array)
print("Reversed array")
print(reverse_array)Output:
C:\Users\username>python array_reverse.py
Original array
array('i', [1, 2, 3, 4, 5])
Reversed array
array('i', [5, 4, 3, 2, 1])In the above example, we create an array of five elements and reverse the array elements using negative indexing.
insert() method
The insert() method is used to insert the array elements at a given index.
import array as arr
my_array = arr.array('i', [1, 2, 3, 4, 5])
reverse_array = arr.array('i')
for i in my_array:
reverse_array.insert(0, i)
print("Original array")
print(my_array)
print("Reversed array")
print(reverse_array)Output:
C:\Users\username>python array_reverse.py
Original array
array('i', [1, 2, 3, 4, 5])
Reversed array
array('i', [5, 4, 3, 2, 1])In the above example, we create an array of five elements and reverse the array elements using the insert() method.
reverse() method
The reverse() method is used to reverse the order of the items in the array.
import array as arr
my_array = arr.array('i', [1, 2, 3, 4, 5])
my_array.reverse()
print("Reversed array")
print(my_array)Output:
C:\Users\username>python array_reverse.py
Reversed array
array('i', [5, 4, 3, 2, 1])In the above example, we create an array of five elements and reverse the array elements using the reverse() method.
Sorting Array
Sort the array elements in ascending or descending order using the sort() method.
Using Sorting Algorithm (Bubble Sort)
Bubble sort algorithm is used to sort the array elements in ascending order.
import array as arr
my_array = arr.array('i', [5, 2, 3, 4, 1])
for i in range(len(my_array)):
for j in range(i + 1, len(my_array)):
if my_array[i] > my_array[j]:
temp = my_array[i]
my_array[i] = my_array[j]
my_array[j] = temp
print(my_array)Output:
C:\Users\username>python array_sort.py
array('i', [1, 2, 3, 4, 5])In the above example, we create an array of five elements and sort the array elements in ascending order using the bubble sort algorithm.
Using Sorting Algorithm (Selection Sort)
Selection sort algorithm is used to sort the array elements in ascending order.
import array as arr
my_array = arr.array('i', [5, 2, 3, 4, 1])
for i in range(len(my_array)):
min_index = i
for j in range(i + 1, len(my_array)):
if my_array[min_index] > my_array[j]:
min_index = j
temp = my_array[i]
my_array[i] = my_array[min_index]
my_array[min_index] = temp
print(my_array)Output:
C:\Users\username>python array_sort.py
array('i', [1, 2, 3, 4, 5])In the above example, we create an array of five elements and sort the array elements in ascending order using the selection sort algorithm.
sort() method
The sort() method is used to sort the array elements in ascending order.
import array as arr
my_array = arr.array('i', [5, 2, 3, 4, 1])
my_array.sort()
print(my_array)Output:
C:\Users\username>python array_sort.py
array('i', [1, 2, 3, 4, 5])In the above example, we create an array of five elements and sort the array elements in ascending order using the sort() method.
Using Sorted() Function
The sorted() function is used to sort the array elements in ascending order.
import array as arr
my_array = arr.array('i', [5, 2, 3, 4, 1])
new_array = sorted(my_array)
print(new_array)Output:
C:\Users\username>python array_sort.py
[1, 2, 3, 4, 5]In the above example, we create an array of five elements and sort the array elements in ascending order using the sorted() function.
Searching Array
Search the array elements using the index() method and in operator.
index() method
The index() method returns the index of the specified element in the array.
import array as arr
my_array = arr.array('i', [1, 2, 3, 4, 5])
data = my_array.index(3)
print(data)Output:
C:\Users\username>python array_search.py
2In the above example, we create an array of five elements and search the array elements using the index() method.
in operator
The in operator returns True if the specified element is present in the array.
import array as arr
my_array = arr.array('i', [1, 2, 3, 4, 5])
print(3 in my_array)Output:
C:\Users\username>python array_search.py
TrueIn the above example, we create an array of five elements and search the array elements using the in operator.
Joining Array
Join the array elements using the + operator and extend() method.
+ operator
The + operator is used to join the array elements.
import array as arr
my_array1 = arr.array('i', [1, 2, 3, 4, 5])
my_array2 = arr.array('i', [6, 7, 8, 9, 10])
new_array = my_array1 + my_array2
print(new_array)Output:
C:\Users\username>python array_join.py
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])In the above example, we create two arrays of five elements and join the array elements using the + operator.
extend() method
The extend() method is used to join the array elements.
import array as arr
my_array1 = arr.array('i', [1, 2, 3, 4, 5])
my_array2 = arr.array('i', [6, 7, 8, 9, 10])
my_array1.extend(my_array2)
print(my_array1)Output:
C:\Users\username>python array_join.py
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])In the above example, we create two arrays of five elements and join the array elements using the extend() method.
Using fromlist() method
The fromlist() method is used to join the array elements.
import array as arr
my_array1 = arr.array('i', [1, 2, 3, 4, 5])
my_array2 = arr.array('i', [6, 7, 8, 9, 10])
my_array1.fromlist(my_array2.tolist())
print(my_array1)Output:
C:\Users\username>python array_join.py
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])In the above example, we create two arrays of five elements and join the array elements using the fromlist() method.
Using list() function
The list() function is used to join the array elements.
import array as arr
my_array1 = arr.array('i', [1, 2, 3, 4, 5])
my_array2 = arr.array('i', [6, 7, 8, 9, 10])
my_array1 = arr.array('i', list(my_array1) + list(my_array2))
print(my_array1)Output:
C:\Users\username>python array_join.py
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])In the above example, we create two arrays of five elements and join the array elements using the list() function.
Conclusion
In this tutorial, you have learned how to perform operations on arrays. how to perform loop, copy, reverse, sort, search, and join operations on arrays. Now you can solve problems on arrays using Python. If you like this tutorial, please share it with others via the social media channel. Thanks for reading. For more tutorials, please visit Python Central Hub.
flowchart TD
A["array('i',[1,2]) + array('i',[3])"] --> B["array('i', [1, 2, 3]) -- CONCATENATION"]
C["array('i',[1,2]) * 2"] --> D["array('i', [1, 2, 1, 2]) -- REPETITION"]
E["you wanted element-wise?"] --> F["a comprehension, one Python call per element"]
E --> G["or numpy, where + IS element-wise"]
B --> H["both operands must share a typecode"]
H --> I["otherwise TypeError"]
Check yourself
What does `array('i',[1,2]) + array('i',[3,4])` produce?
Concatenation, exactly as with lists. `array` is a sequence type with compact storage — it adds no arithmetic semantics at all.
Show answer
B — `array('i', [1, 2, 3, 4])` — Concatenation, exactly as with lists. `array` is a sequence type with compact storage — it adds no arithmetic semantics at all.
How do you double every element of an `array`?
`a * 2` repeats the sequence. A comprehension costs one Python-level operation per element and gives back a list; NumPy does it element-wise in C.
Show answer
C — A comprehension, or use NumPy — `a * 2` repeats the sequence. A comprehension costs one Python-level operation per element and gives back a list; NumPy does it element-wise in C.
When is `array` the right choice over NumPy?
It is in the standard library and has `tofile`/`fromfile` built in. The moment you want arithmetic across the block, NumPy is the better tool.
Show answer
B — A compact block you mostly store, or read and write to a file — and you want no dependency — It is in the standard library and has `tofile`/`fromfile` built in. The moment you want arithmetic across the block, NumPy is the better tool.
What must be true to concatenate two arrays?
The result is a single block of one fixed width, so both operands must agree on the type. Mixing typecodes raises `TypeError`.
Show answer
B — They must share a typecode — The result is a single block of one fixed width, so both operands must agree on the type. Mixing typecodes raises `TypeError`.
Try it: Array Operations Exercises
Exercise 1 – Concatenate Arrays
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 2 – Search in Array
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 3 – Sum of Array
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.