Main content
AP®︎/College Computer Science Principles
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:0 | 1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|---|
"red" | "orange" | "yellow" | "green" | "blue" | "indigo" | "violet" |
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!" 🎶
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!
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):
index | item |
---|---|
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.index | item | |
---|---|---|
→ | 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.
index | item | |
---|---|---|
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".
index | item |
---|---|
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);
index | item |
---|---|
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!
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:
DISPLAY(list[1])
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?
- So when u removed an item from the middle, the index numbers remained the same. Will it now change to reflect numbers in sequence?(1 vote)
- If you remove an item the index number has to change as well unless you're fine with having an empty spot.
Say you have a list
0 - Learn Math
1 - Play
2 - Learn Comp Sci
and you remove Play, then you have the list
0 - Learn Math
1 - Learn Comp Sci
or if you don't remove the second slot (say you're working with an array and don't want to the work of moving around the other items in the list)
0 - Learn Math
1 - <empty>
2 - Learn Comp Sci(11 votes)
- When you first introduced storing and updating lists protocol with JavaScipt then to pseudocode it made it a bit confusing.(4 votes)
- From the author:Thanks for the feedback! Are you taking the CSP exam? If you're not, you don't need to worry about learning pseudocode. (And you might be interested in our Intro to JS course instead).
Would it help if there was a bigger visual transition to the pseudocode section?(5 votes)
- 3 in pseudocode in 2 in index?(1 vote)
- Yes, since pseudocode initiates with 1 instead of 0.(4 votes)
- what are list procedures?(1 vote)
- Functions used to get information from lists and change the lists(1 vote)
- So, let's just say I have a list of numbers. How would I add those numbers that are in the list (for the record, I do not want to append items to the list)?(0 votes)
- If you want to find the sum of elements in a list, certain programming languages will provide built-in functions for this. Alternatively, you can use a for-loop to access each element of the list and add them together, one at a time.(2 votes)
- For the last pseudocode would it be
Scare ants away
Wash the dishes
Write this article
Do laundry
Mow the lawn?
I am somewhat confused as how the order of index would be affected after inserting an item(0 votes) - In the "Lists with Pseudocode" section, it includes the following:
DISPLAY(list[1])
list[1] ← 55
Why does the assignment come after the display?(0 votes) - 2 questions regarding pseudocode:
In pseudocode, can we write an insert+remove likemyList.splice(0, 2, "list item");
where you remove 2 items after adding "list item" at index 0? Or do we always have to separateINSERT
andREMOVE
?
Also, do you always have to writeREMOVE
as removing specific indexes or is there pseudocode to remove a specific number of items, in bulk?(0 votes) - 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.*
This section doesn't make sense to me. What does it mean by "1-based index i"? Aren't indices ordered by numbers? where is index i located in an array?(0 votes)- "i" is simply the name of the variable representing the index. It does not mean that we are literally inserting an item at index number "i".(1 vote)