Solution Review: Appending an Element to a List

In the following lesson, we will go over the solution of the challenge: Appending an Element to a List

We'll cover the following

Task

In this challenge, you were provided a list. Your task was to append an element to the list having the same value as the first element of the same list.

Solution

The task required you to use the append List operator :+ which appends an element to the end of a list. The operator has two operands:

  • The first operand is the list to which you wish to append an element.
  • The second operator is the element you wish to append to the end of a list.

In our case, the first operand would be list and the second operand would be list(0). list(0) is accessing the first element of list.

You can find the complete solution below:

You were required to write the code on line 2.

Press + to interact
val list = List("a","b","c")
val finalList = list :+ list(0)
// Driver Code
finalList.foreach(println)

In the next lesson, we will move on to vectors.