Arrays - Python
Arrays are used to store multiple values in one single variable.
Create an array containing car names:
cars = ["Ford", "Volvo", "BMW"]
print(cars)
====o/p====
['Ford', 'Volvo', 'BMW']
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
An array is a special variable, which can hold more than one value at a time.
An array can hold many values under a single name, and you can access the values by referring to an index number.
We refer to an array element by referring to the index number.
cars = ["Ford", "Volvo", "BMW"]
x = cars[0]
print(x)
====o/p====
Ford
Modify the value :
Modify the value of the first array item:
cars = ["Ford", "Volvo", "BMW"]
cars[0] = "Toyota"
print(cars)
====o/p====
['Toyota', 'Volvo', 'BMW']
cars=["Benz","BMW","Rangerover"]
x = len(cars)
print(x)
===o/p====
3
Note: The length of an array is always one more than the highest array index.
You can use the for in loop to loop through all the elements of an array.
cars = ["Benz", "Nano", "BMW"]
for i in cars:
print(i)
====o/p====
Benz
Nano
BMW
You can use the append( ) method to add an element to an array.
cars = ["Honda", "Benz", "BMW"]
cars.append("Rangerover")
print(cars)
====o/p=====
['Honda', 'Benz', 'BMW', 'Rangerover']
You can use the pop( ) method to remove an element from the array.
cars = ["Benz", "Volvo", "BMW"]
cars.pop(2)
print(cars)
====o/p====
['Benz', 'Volvo']
You can also use the remove( ) method to remove an element from the array.
cars = ["Ford", "Volvo", "BMW"]
cars.remove("Volvo")
print(cars)
====o/p====
['Ford','BMW']
Note: The list's remove() method only removes the first occurrence of the specified value.
Method | Description |
---|---|
append( ) | Adds an element at the end of the list |
clear( ) | Removes all the elements from the list |
copy( ) | Returns a copy of the list |
count( ) | Returns the number of elements with the specified value |
extend( ) | Add the elements of a list (or any iterable), to the end of the current list |
index( ) | Returns the index of the first element with the specified value |
insert( ) | Adds an element at the specified position |
pop( ) | Removes the element at the specified position |
remove( ) | Removes the first item with the specified value |
reverse( ) | Reverses the order of the list |
sort( ) | Sorts the list |