Python Arrays
- Previous Page Python Lambda
- Next Page Python Class/Object
Please note that Python does not have built-in support for arrays, but Python lists can be used instead.
Array
Arrays are used to store multiple values in a single variable:
Instance
Create an array containing car brands:
cars = ["Porsche", "Volvo", "BMW"]
What is an array?
An array is a special variable that can contain multiple values at once.
If you have a list of items (such as, a list of car brands), storing the brand in a single variable may look like this:
car1 = "Porsche" car2 = "Volvo" car3 = "BMW"
But what if you want to traverse these brands and find a specific car brand? What if it's not 3 cars but 300 cars?
The solution is an array!
An array can save multiple values under a single name, and you can access these values by referencing the index number.
Access array elements
Reference array elements by index.
Instance
Get the value of the first array item:
x = cars[0]
Instance
Modify the value of the first array item:
cars[0] = "Audi"
Array length
Use len()
Method to return the length of the array (the number of elements in the array).
Instance
Return the number of elements in the cars array:
x = len(cars)
Note:The array length is always one more than the highest array index.
Loop through array elements
You can use for in
Loop through all elements of the array.
Instance
Print each item in the cars array:
for x in cars: print(x)
Add array elements
You can use append()
The method adds an element to the array.
Instance
Add another element to the cars array:
cars.append("Audi")
Delete array elements
You can use pop()
The method removes elements from the array.
Instance
Delete the second element of the cars array:
cars.pop(1)
You can also use remove()
The method removes elements from the array.
Instance
Delete the element with the value "Volvo":
cars.remove("Volvo")
Note:The list of remove()
The method only deletes the first occurrence of the specified value.
Array Methods
Python provides a set of built-in methods that can be used on lists or arrays.
Method | Description |
---|---|
append() | Add an element at the end of the list |
clear() | Delete all elements in the list |
copy() | Return a copy of the list |
count() | Return the number of elements with specified values |
extend() | Add list elements (or any iterable elements) to the end of the current list |
index() | Return the index of the first element with specified values |
insert() | Add elements at specified positions |
pop() | Delete elements at specified positions |
remove() | Delete items with specified values |
reverse() | Reverse the order of the list |
sort() | Sort a list |
Note:Python does not have built-in support for arrays, but can be used with Python lists instead.
- Previous Page Python Lambda
- Next Page Python Class/Object