Arrays - adamjberg/coding-curriculum GitHub Wiki
An Array is a Data Structure that allow storing multiple values in a single variable.
array = [1, 2, 3, 4]
print(array[0])
// Output: 1
To access elements of an array, use the []
operator. Arrays are typically indexed starting at 0*. This means that the first element will be accessed by typing the array variable name followed by [0]
e.g. array[0]
.
The third element will be accessed using array[2]
. Because the array starts at index 0, the index to access the element will be one less than 3.
Attempting to access an element outside the range of an array will normally result in an error. If we have an array of length 4, accessing array[4]
will throw an error.
Below are the methods on a Python list. Other languages will have similar functionality, but the naming might be slightly different.
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 |
This is one of the most common things you will do with an array. Iterating over the array allows you to perform some operation(s) on each element of the array.
array = [1, 2, 3]
for (i = 0; i < array.length; i++) {
print(array[i])
}
// Output: 1 2 3
fruits = ["apple", "banana", "cherry"]
- Print the second item in the fruits list.
- Change the value from "apple" to "kiwi", in the fruits list.
- Use the append method to add "orange" to the fruits list.
- Use the insert method to add "lemon" as the second item in the fruits list.
- Use the remove method to remove "banana" from the fruits list.
- Use negative indexing to print the last item in the list.
- Use a range of indexes to print the third, fourth, and fifth item in the list.
- Use the correct syntax to print the number of items in the list.
* Not the case for all programming languages