What is an Array?
Earlier class we use 3 variables to store 3 different car name (value)
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"
If use Array : only need one array name.
Basic Examples
Example 1: (Store & Print the elements in/from array)
cars = ["Ford", "Volvo", "BMW"]
for x in cars:
print(x)
Example 2 : (Add/Append elements in array)
cars = ["Ford", "Volvo", "BMW"]
cars.append("Honda")
print(cars)
Example 3 : (Remove element from array)
cars = ["Ford", "Volvo", "BMW"]
cars.pop(2)
print(cars)
cars = ["Ford", "Volvo", "BMW"]
cars.remove("Volvo")
print(cars)
Example 4 : (Reverse the order of element in array)
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)
Example 5 : (Extend the array into one array)
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits)
Example 6 : (display the index value of the element)
fruits = ['apple', 'banana', 'cherry']
x = fruits.index("cherry")
print(x)
Example 7 : clear()
prime_numbers = [2, 3, 5, 7, 11, 13]
print('List before clear():', prime_numbers)
# remove all elements
prime_numbers.clear()
# Updated prime_numbers List
print('List after clear():', prime_numbers)
# Output: List after clear(): []
Example 8 : copy()
# creating the first array
arr1 = [2, 6, 9, 4]
# displaying the identity of arr1
print("Array 1",arr1)
# shallow copy arr1 in arr2 using copy()
arr2 = arr1.copy()
# displaying the identity of arr2
print("Array 2",arr2)
# making a change in arr1
arr1[1] = 7
# displaying the arrays
print("Array 1",arr1)
print("Array 2",arr2)
Example 9 : count()
points = [1, 4, 2, 9, 9, 8, 9, 3, 1]
x = points.count(9)
print(x)
fruits = ['apple', 'banana', 'cherry']
x = fruits.count("cherry")
print(x)
Example 10 : insert()
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
print(fruits)
Example 11 : sort()
cars = ['Volvo','Ford', 'BMW', ]
cars.sort()
print(cars)