Creating a Mutable List

Elements can be accessed from any list, but only with mutable lists can we change the contents of our list by adding, replacing, or removing elements. Previously we’ve only created immutable lists; in this exercise, we’ll learn how to create a mutable list and alter its contents.

The syntax for declaring a mutable list is as follows:

var/val listName = mutableListOf(value1, value2, value3) 

A mutable list is defined by the term, mutableListOf as opposed to listOf as we’ve seen previously. Although the syntax and structure of mutable and immutable lists are the same, the compiler knows which operations can or can’t be performed on the list given the term it’s defined with.

Assume we have a list that stores a student’s daily activities:

var dailyActivities = mutableListOf("going to school", "attending tennis practice", "reading")

Now that it’s summertime and there’s no school, we would like to update the first element of our list to reflect the new season. We can take our previous knowledge of accessing elements a step further and assign a new value to an element’s indexed position with the following syntax:

dailyActivities[0] = "swimming at the beach"

The value following the assignment operator will get replaced with the current value at the 0 index. Printing the value of dailyActivities will result in the following output and updated list:

[swimming at the beach, attending tennis practice, reading]



In Broadway.kt, create a mutable list, openBroadwayShows which will store a list of shows that are available for viewing on Broadway. This list should include the following titles:

  • "The Lion King"
  • "Chicago"
  • "The Cher Show"
  • "Les Miserables"

The Cher Show has been closed as of August 2019. Let’s remove it from the list and replace it with a show that’s still open: "Wicked".

Next, use a print statement to output the value of openBroadwayShows and see the updated list.

Folder Icon

Take this course for free

Already have an account?