If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Main content

Storing and updating lists

In programming, variables give us a way to remember a piece of data and give it a name, so that we can access and even change it later. Oftentimes, that data is a single piece of information, like a number or a string.
Sometimes that data is a collection of related information, like a listing of high scores or student names. To store collections like those, computer programs can use the list data type, also known as array or sequence.

Initializing a list

To get started using lists, we need to initialize a variable to store a list.
In the JavaScript language, we call a list an array and use square brackets to store an array:
var myChores = [ ];
That list is completely empty (no chores, woo!), since there are no values inside the brackets.
Here's a list that starts off with 5 numbers:
var lottoNumbers = [8, 9, 32, 37, 39];
Notice that we separate each value by a comma.
We can also store a list of strings, like this example:
var rainbowColors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"];
The syntax is very important here: we surround each value with quotes, since each value is a string, but we put the comma outside the quotes. Grammar rules don't work in JavaScript!

Accessing list values

Now that we know how to store a list, we need a way to retrieve each item inside the list.
The first step is to figure out the index of the desired item. The computer assigns an index to each item of the list, so that it can keep track of where it stored that item in its actual memory.
In the JavaScript language, the first item in a list is at index 0, not at index 1.
Here are the indices for the rainbowColors array:
Now we can reference any item in the array using "bracket notation":
var firstColor = rainbowColors[0];
var lastColor = rainbowColors[6];
The variable firstColor stores "red", and the variable lastColor stores "violet".
List indexing is where programmers often run into "off-by-one errors": that's when your code is almost right, except one number is either too high or too low. Whenever you're programming with lists, keep in mind how indexing works in that language and double check your indices.
🎅🏽"You're making a list, checking it twice!" 🎶
Check your understanding
Consider this list of numbers:
var lottoNumbers = [8, 9, 32, 37, 39];
Given the 0-indexing of arrays in JavaScript, what number is stored in lottoNumbers[1]?
  • Your answer should be
  • an integer, like 6
What's stored in lottoNumbers[4]?
  • Your answer should be
  • an integer, like 6

Updating list values

We can update an item in a list as long as we know its index.
In JavaScript, we use bracket notation to update a value. For example, let's update the colors of the rainbow based on more modern interpretations.
rainbowColors[4] = "cyan";
rainbowColors[5] = "blue";
Now the rainbowColors array will store "red", "orange", "yellow", "green", "cyan", "blue", and "violet".
✏️ The program below stores, displays, and updates a list of my favorite food. Change the program to reflect your favorites instead, and try making the list longer!
📝 See similar code in: App Lab | Snap | Python

List operations

There are many, many ways we can modify a list, besides just updating a singular value, and programming languages often provide built-in procedures for list modification. Let's try a few of them.

Appending an item

We often want to append an item to a list, which means adding a new item to the end of it.
In JavaScript, we can call the push() method on an array, and pass the new item as a parameter.
Remember my empty myChores array from earlier? Well…
myChores.push("Wash the dishes");
Not so empty anymore! Now the list stores a single item, "Wash the dishes". We can keep adding items as needed, and the list will get longer each time.
myChores.push("Do laundry");
myChores.push("Mow the lawn");
The list now has 3 items (unfortunately for me):
0"Wash the dishes"
1"Do laundry"
2"Mow the lawn"

Inserting an item

Sometimes we want to add an item earlier in the list, like at the beginning or between two existing items.
One way to do that in JavaScript is with the splice() method.
myChores.splice(0, 0, "Scare ants away");
The splice method takes 3 parameters: the index where it should insert the item, the number of items to remove, and the item to insert. In the example above, the index is 0 and the number to remove is 0, so that code will insert an item in the very first position and shift all the items after by one index.
0"Scare ants away"
1"Wash the dishes"
2"Do laundry"
3"Mow the lawn"
The myChores array now stores 4 values.
We can also insert an item in the middle of the list:
myChores.splice(2, 0, "Write this article");
In this case, the code inserts the new item at index 2 and shifts the items after it.
0"Scare ants away"
1"Wash the dishes"
2"Write this article"
3"Do laundry"
4"Mow the lawn"
The array now stores 5 values. Notice that the first two items stayed at the same index, since this splice operation did not affect them at all.
Are you getting nervous about memorizing exactly how to use methods like splice()? Don't worry, you can always look up documentation and examples. Programmers don't need to memorize the details of every procedure and parameter, it's more important that we understand the range of options that exist and that we know how to find more details.

Removing an item

Of course, we can also remove items from lists.
In JavaScript, one way to remove items is with that same splice() method. The second parameter to splice() specifies the number of items to remove, so if we specify a non-zero number and do not provide a third parameter, then we can remove an item.
myChores.splice(4, 1);
That line of code specifies an index of 4 and a number to remove of 1, so it removes a single item at index 4. Since the array is only 5 items long, that removes the last item, "Mow the lawn".
0"Scare ants away"
1"Wash the dishes"
2"Write this article"
3"Do laundry"
We can also remove items in the middle of a list. I'm pretty much done with writing this article, so I can remove that item, at index 2.
myChores.splice(2, 1);
0"Scare ants away"
1"Wash the dishes"
3"Do laundry"
Now my list of chores is only 3 items long, much more manageable.
✏️ Ever made a playlist on a music website? Most sites give you the ability to add new songs to the list, move songs around, and remove songs. The program below is a simple playlist editor using lists. Play around with it, replace my outdated songs with your favorite hits!
📝 See similar code in: App Lab | Snap | Python

Lists in pseudocode

Many languages use bracket notation for lists, and that's what we use in pseudocode as well.
This pseudocode represents initializing a list with 3 items:
list ← [1, 2, 3]
Similarly, we can use bracket notation to access and assign items:
list[1] ← 55
⚠️ There's a big difference between the AP CSP exam pseudocode and the JavaScript code: the list indices start at 1. That code above displays the first item in the list, not the second.
There are a number of programming languages that use 1-based indexing, especially those popular with mathematicians, so it's important to know how indexing works in whatever language or pseudocode you're currently using.
Given those differences, here's the pseudocode for storing and updating the list of rainbow colors:
rainbowColors ← ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]

firstColor ← rainbowColors[1]
lastColor ← rainbowColors[7]

rainbowColors[5] ← "cyan"
rainbowColors[6] ← "blue"

List operations

When it comes to list operations, there's quite a bit of variation across languages.
Here's how we can represent appending an item in pseudocode:
APPEND(list, item)
That procedure adds item to the end of list, increasing the length of list by 1.
INSERT(list, i, item)
That procedure inserts the item at the 1-based index i, and shifts any items after to the right. The length of the list increases by one.
REMOVE(list, i)
That procedure removes the item at the 1-based index i, and shifts any items after to the left. The length of the list decreases by one.
We can rewrite the operations of the myChores list using pseudocode like so:
myChores ← []

APPEND(myChores, "Wash the dishes")
APPEND(myChores, "Do laundry")
APPEND(myChores, "Mow the lawn")

INSERT(myChores, 1, "Scare ants away")
INSERT(myChores, 3, "Write this article")

REMOVE(myChores, 5)
REMOVE(myChores, 3)

🙋🏽🙋🏻‍♀️🙋🏿‍♂️Do you have any questions about this topic? We'd love to answer— just ask in the questions area below!

Want to join the conversation?