5 Array
5 Array
Array
1. CREATING AN ARRAY
import array as arr
a = arr.array('d', [1.1, 3.5, 4.5])
print(a)
import array as arr
a = arr.array('i', [1, 2, 3])
print("The new created array is : ", end=" ")
for i in range(0, 3):
print(a[i], end=" ")
import array as arr
b = arr.array('d', [2.5, 3.2, 3.3])
print("\nThe new created array is : ", end=" ")
for i in range(0, 3):
print(b[i], end=" ")
OUTPUT
array('d', [1.1, 3.5, 4.5])
The new created array is : 1 2 3
The new created array is : 2.5 3.2 3.3
3. ACCESS AN ELEMENT
import array as arr
a = arr.array('i', [1, 2, 3, 4, 5, 6])
print("Access element is: ", a[0])
print("Access element is: ", a[3])
b = arr.array('d', [2.5, 3.2, 3.3])
print("Access element is: ", b[1])
print("Access element is: ", b[2])
OUTPUT
Access element is: 1
Access element is: 4
Access element is: 3.2
Access element is: 3.3
colors = ["red", "green", "blue"]
print(colors[0])
print(colors[2])
OUTPUT
red
blue
5. MODIFYING AN ELEMENT
fruits = ["apple", "banana", "orange", "grape"]
fruits[1] = "kiwi"
print(fruits)
OUTPUT
['apple', 'kiwi', 'orange', 'grape']
import array
arr = array.array('i', [1, 2, 3, 1, 2, 5])
print("Array before updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
print("\r")
arr[2] = 6
print("Array after updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
print()
arr[4] = 8
print("Array after updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
OUTPUT
Array before updation : 1 2 3 1 2 5
Array after updation : 1 2 6 1 2 5
Array after updation : 1 2 6 1 8 5
6. SLICING OF AN ARRAY
import array as arr
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = arr.array('i', l)
print("Initial Array: ")
for i in (a):
print(i, end=" ")
Sliced_array = a[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_array)
Sliced_array = a[5:]
print("\nElements sliced from 5th element till the end: ")
print(Sliced_array)
Sliced_array = a[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_array)
OUTPUT
Initial Array:
1 2 3 4 5 6 7 8 9 10
Slicing elements in a range 3-8:
array('i', [4, 5, 6, 7, 8])
Elements sliced from 5th element till the end:
array('i', [6, 7, 8, 9, 10])
Printing all elements using slice operation:
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])