Menu
Coddy logo textTech

Sequence Operators

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 81 of 93.

Kotlin provides the + operator for combining lists, making it easy to merge collections together. This works similarly to how you concatenate strings.

To join two lists into one, simply use the + operator:

val first = listOf(1, 2, 3)
val second = listOf(4, 5, 6)
val combined = first + second
println(combined)  // [1, 2, 3, 4, 5, 6]

You can also add a single element to a list using the same operator:

val colors = listOf("Red", "Green")
val moreColors = colors + "Blue"
println(moreColors)  // [Red, Green, Blue]

The - operator removes elements from a list. It creates a new list without the specified element:

val numbers = listOf(1, 2, 3, 2, 4)
val result = numbers - 2
println(result)  // [1, 3, 2, 4]

Notice that only the first occurrence of the element is removed. To remove all matching elements, you would subtract a list instead:

val numbers = listOf(1, 2, 3, 2, 4)
val result = numbers - listOf(2)
println(result)  // [1, 3, 4]

These operators always return a new list: the original lists remain unchanged. This makes them safe to use without worrying about accidentally modifying your data.

challenge icon

Challenge

Medium

You will receive two lists of integers and a single integer to remove. Combine the two lists using the + operator, then remove all occurrences of the specified integer using the - operator with a list.

Print the resulting list.

Input format:

  • First line: an integer n representing the number of elements in the first list
  • Next n lines: integers for the first list
  • Next line: an integer m representing the number of elements in the second list
  • Next m lines: integers for the second list
  • Last line: the integer to remove from the combined list

Output format:

Print the resulting list in Kotlin's default list format.

Example:

If the first list is [1, 2, 3], the second list is [2, 4, 2], and the number to remove is 2, the combined list would be [1, 2, 3, 2, 4, 2]. After removing all occurrences of 2, the output should be:

[1, 3, 4]

Try it yourself

fun main() {
    // Read first list
    val n = readLine()!!.toInt()
    val list1 = mutableListOf<Int>()
    repeat(n) {
        list1.add(readLine()!!.toInt())
    }
    
    // Read second list
    val m = readLine()!!.toInt()
    val list2 = mutableListOf<Int>()
    repeat(m) {
        list2.add(readLine()!!.toInt())
    }
    
    // Read the integer to remove
    val toRemove = readLine()!!.toInt()
    
    // TODO: Write your code here
    // Combine the two lists using + operator
    // Remove all occurrences of toRemove using - operator with a list
    
    // Print the resulting list
    println(result)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground