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

Accessing Elements of an Array

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.

Common Array Methods and Properties*

Python List Built-in Methods

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

Iterating Through an Array

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

Excercises

fruits = ["apple", "banana", "cherry"]
  1. Print the second item in the fruits list.
  2. Change the value from "apple" to "kiwi", in the fruits list.
  3. Use the append method to add "orange" to the fruits list.
  4. Use the insert method to add "lemon" as the second item in the fruits list.
  5. Use the remove method to remove "banana" from the fruits list.
  6. Use negative indexing to print the last item in the list.
  7. Use a range of indexes to print the third, fourth, and fifth item in the list.
  8. Use the correct syntax to print the number of items in the list.

Source

* Not the case for all programming languages

⚠️ **GitHub.com Fallback** ⚠️