What is an Array in Python

Learn this blog what is an array in python, how to calculate elements, length of the elements, Add elements in an array, How to Remove elements in array

What is an Array in Python

An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

car1 = “Ford”
car2 = “Volvo”
car3 = “BMW”

An array can hold many values under a single name, and you can access the values by referring to an index number.

Access the Elements of an Array

You refer to an array element by referring to the index number.

Get the value of the first array item:

Example

cars = [“Ford”, “Volvo”, “BMW”]

x = cars[0]

print(x)

Output:

Ford

Modify the value of the first array item:

Example:

cars = [“Ford”, “Volvo”, “BMW”]

cars[0] = “Toyota”

print(cars)

Output:

[‘Toyota’, ‘Volvo’, ‘BMW’]

The Length of an Array

Use the len() method to return the length of an array (the number of elements in an array)

Example:

cars = [“Ford”, “Volvo”, “BMW”]

x = len(cars)

print(x)

Output:

3

Looping Array Elements

You can use the for in loop to loop through all the elements of an array.

Example:

cars = [“Ford”, “Volvo”, “BMW”]

for x in cars:
print(x)

Output:

Ford
Volvo
BMW

Adding Array Elements

You can use the append() method to add an element to an array.

Example:

cars = [“Ford”, “Volvo”, “BMW”]

cars.append(“Honda”)

print(cars)

Output:
[‘Ford’, ‘Volvo’, ‘BMW’, ‘Honda’]

Removing Array Elements

You can use the pop()or remove() method to remove an element from the array.

Delete the second element of the cars array

Example:

cars = [“Ford”, “Volvo”, “BMW”]

cars.pop(1)

print(cars)

Output:

[‘Ford’, ‘BMW’]

REFERENCE:

https://www.w3schools.com/python/python_arrays.asp