Python Arrays

Arrays
When we want to store multiple values in a single variable then in that case arrays are used.
For e.g. if we want to create an array that will contain the name of cars then we write the following code in python:

cars = ["Ford", "Volvo", "BMW"]


What is an Array?
An array can be defined as a special variable that is capable of holding more than one value at a time.

For e.g. if you are having a list of itms we can say that a list of cars that will store the cars names in a single variable then it would look like as follows:

car1 = "Ford"

car2 = "Volvo"

car3 = "BMW"


The question arises that if you want to loop through the cars and want to find a specific one and if there are 300 cars and not 3 then what is the solution of that>

The solution for this problem is an array!

An array may hold more than one value under a single name and you can access to the values just by reffering to the index number of that.

Access the Elements of an Array
You may refer to an element of an array just by referring to the index number of that element.
For e.g. if you want to get the value of the first array item, then you can write the following code:

x = cars[0]


If you want to modify the value of the first array item, then you can write the following code:

cars[0] = "Toyota"


The Length of an Array
If you want to find the length of an array then you need to use the len() method i.e. the len() function returns the number of elements present in an array.
If you want to return the number of elements present in the cars array, then you can write the following code:

x = len(cars)


Looping Array Elements
If you want to loop through all the elements of the array then you use the for loop for this purpose.
For e.g. if you want to print every item in the cars array, then you can write then following code:

for x in cars:

     print(x)


Adding Array Elements
If you want to add an element to an array then you have to use the append() function for this purpose.
For e.g. if you want to add one more element to the cars array, then you can write the following code:

cars.append("Honda")


Removing Array Elements
If you want to remove an element from an array then you have to use the pop() function for this purpose.
For e.g. if you want to delete the second element of the cars from the array, then you can write the following code:

cars.pop(1)


You can also use the remove() function to remove an element from the array.
For e.g. if you want to delete the element from array that has the value "Volvo":

cars.remove("Volvo")