Various array operations
a = [1, "Hello", [3.14, "world"]]
a.append(2) # Add an integer to the end
print(a)
Output
[1, 'Hello', [3.14, 'world'], 2]
2) Python Array Example:
import array as arr
# creating array of integers
a = arr.array('i', [1, 2, 3])
# accessing First Araay
print(a[0])
# Adding element to array
a.append(5)
print(a)
Output
1
array('i', [1, 2, 3, 5])
3)Create an Array in Python
import array as arr
# creating array
a = arr.array('i', [1, 2, 3])
# iterating and printing each item
for i in range(0, 3):
print(a[i], end=" ")
Output
1 2 3
4) Adding Elements to an Array
import array as arr
# Integer array example
a = arr.array('i', [1, 2, 3])
print("Integer Array before insertion:", *a)
a.insert(1, 4) # Insert 4 at index 1
print("Integer Array after insertion:", *a)
Output
Integer Array before insertion: 1 2 3
Integer Array after insertion: 1 4 2 3
5)Accessing Array Items
import array as arr
a = arr.array('i', [1, 2, 3, 4, 5, 6])
print(a[0])
print(a[3])
b = arr.array('d', [2.5, 3.2, 3.3])
print(b[1])
print(b[2])
Output
1
4
3.2
3.3
6) Removing Elements from the Array
import array
arr = array.array('i', [1, 2, 3, 1, 5])
# using remove() method to remove first occurance of 1
arr.remove(1)
print(arr)
# pop() method - remove item at index 2
arr.pop(2)
print(arr)
Output
array('i', [2, 3, 1, 5])
array('i', [2, 3, 5])
7) Slicing of an Array- to print a specific range of elements from the array, we
use Slice operation .
import array as arr
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = arr.array('i', l)
Sliced_array = a[3:8]
print(Sliced_array)
Sliced_array = a[5:]
print(Sliced_array)
Sliced_array = a[:]
print(Sliced_array)
Output
array('i', [4, 5, 6, 7, 8])
array('i', [6, 7, 8, 9, 10])
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
8)Updating Elements in an Array
import array
arr = array.array('i', [1, 2, 3, 1, 2, 5])
# update item at index 2
arr[2] = 6
print(arr)
# update item at index 4
arr[4] = 8
print(arr)
Output
array('i', [1, 2, 6, 1, 2, 5])
array('i', [1, 2, 6, 1, 8, 5])
9) Reversing Elements in an Array
import array
arr = array.array('i', [1, 2, 3, 4, 5])
arr.reverse()
print("Reversed array:", *arr)
Output
Reversed array: 5 4 3 2 1
10) Extend Element from Array
import array as arr
a = arr.array('i', [1, 2, 3,4,5])
# using extend() method
a.extend([6,7,8,9,10])
print(a)
Output
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])