Arrays

Note: This lesson covers JavaScript and Python.

Definition

The basic structure to store several values in a sequence is called an array in JavaScript and a list in Python. Both are used to hold multiple elements under a single name.

Syntax

arrays/list

There are various ways of creating an array/list.

  1. Literal
    var array_name = [element0, element1, element2,... elementN];
  2. General
    var array_name = [];
    array_name[0] = element0;
    array_name[1] = element1;
    array_name[2] = element2;
    ... 
    array_name[N] = elementN;
  1. Literal
    list_name = [element0, element1, element2,... elementN]
  2. General
    list_name = []
    list_name[0] = element0
    list_name[1] = element1
    list_name[2] = element2
    ... 
    list_name[N] = elementN

Access / Change value by index


marksValue 76 34 65 25 49 57
Index 0 1 2 3 4 5
  1. Create array/list - In our example below, we create an array/list named marks which has six elements.
  2. Access value by index - We can access a value by referring to its index number. Indexes start at zero:
    • marks[0] is the first value - 76.
    • marks[1]is the second value - 34.
    • marks[5]is the last value - 57.
  3. Change value by index - We can change a value by specifying the index number and the new value. Our example selects index zero, marks[0], to modify the first value in the list.
  1. Create Array
    var marks = [76, 34, 65, 25, 49, 57];
  2. Access value by index
    alert(marks[0]);    // 76
    alert(marks[1]);    // 34
  3. Change value by index
    marks[0] = 80;    // [80, 34, 65, 25, 49, 57]
    
  1. Create List
    marks = [76, 34, 65, 25, 49, 57]
  2. Access value by index
    print(marks[0])    # 76
    print(marks[1])    # 34
  3. Change value by index
    marks[0] = 80    # [80, 34, 65, 25, 49, 57]
    

Adding end element

Each language has a built in method to add an element to the end of the array/list.

JavaScript uses push() and Python uses append().

var marks = [76, 34, 65, 25, 49, 57];
marks.push(18);       // [76, 34, 65, 25, 49, 57, 18];
marks.push(79, 31);   // [76, 34, 65, 25, 49, 57, 18, 79, 31];
marks = [76, 34, 65, 25, 49, 57]
marks.append(18)    
# [76, 34, 65, 25, 49, 57, 18]

Removing end element

Each language has a built in method to remove an element from the end of the array/list.

var marks = [76, 34, 65, 25, 49, 57]
// remove last value
marks.pop();   // [76, 34, 65, 25, 49]
marks = [76, 34, 65, 25, 49, 57]
# remove last value
marks.pop()    # [76, 34, 65, 25, 49] 
#remove value at index 1
marks.pop(1)   # [76, 65, 25, 49]

Length of array/list

The example code below shows how the number of elements in the array/list can be determined.

This example also shows that a JavaScript array and Python list can contain elements of different types.

var results = ["Exam", 76, 34, 65, 25, 49, 57];
alert(results.length);     // 7
results = ["Exam", 76, 34, 65, 25, 49, 57]
print(len(results))         # 7