HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to ScalaVariables (val / var)Data TypesStringsListsConditions (if / match)Loops (for / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables & Types
🔢 Numbers & Math
✍️ String
📚 Collection
🔀 Condition & Loop
🧩 Function
Scala›Lists

Lists

List creation, element access, size, and transformation with map.

Simple enough for a 5-year-old to understand

Create and access a list

In Scala, a List is immutable. Elements are accessed using a zero-based index.

Example code
1
val colors = List("red", "purple", "green")
A list with three elements.
DataA list with three elements.
2
println(colors(0))
First element: red
Output / InputFirst element: red
3
println(colors.length)
Number of elements: 3
Output / InputNumber of elements: 3
DataOutput / Input
💡 Hint: In Scala, elements are accessed using parentheses instead of square brackets.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.How do you access the first element of a list in Scala?

About this topic

The default list in Scala is immutable and has a linked structure. When you add elements, the existing list does not change; a new list is produced. This is the core approach of functional programming and makes sharing safe in concurrent code.

The linked structure determines the costs: prepending is done in constant time, while appending requires traversing the entire list. This difference is noticeable in large lists, and choosing the correct operator directly affects performance.

The collection library is one of Scala's strongest points. Transformation, filtering, grouping, and reduction operations come out of the box; by chaining them, you can build complex transformations without writing loops.

What you will learn

  • Creating lists and accessing elements
  • Prepending and appending operators
  • The consequences of immutability
  • Transformation and filtering operations
  • Safe access methods

Who is this for?

  • Developers who will work with collections
  • Learners of immutable data structures
  • Engineers who will process data with Spark

When to use?

Immutable collections are standard in data transformation pipelines; each step produces a new collection, and intermediate results remain intact.

If many insertions are going to be made, using a mutable builder and converting it to an immutable one at the end is both fast and safe.

Common mistakes

Wrong

val liste = List(1, 2, 3)
liste(5)

There are only three elements in the list; when the sixth position is requested, an IndexOutOfBoundsException is thrown and the program stops. Additionally, lists have a linked structure, so index access counts from the beginning and is not as cheap as one might think.

Correct

val liste = List(1, 2, 3)
println(liste.lift(5).getOrElse("none"))

Wrong

var liste = List(1, 2, 3)
for (i <- 1 to 1000) {
  liste = liste :+ i
}

The append operator copies the entire list at each step; in a thousand steps, the number of operations increases rapidly and the code slows down unnecessarily. The correct pattern is to prepend and reverse at the end, or use a builder.

Correct

val liste = (1 to 1000).toList
println(liste.length)

Wrong

val liste = List(1, 2, 3)
println(liste.head)
println(List().head)

An empty list has no first element, and a NoSuchElementException is thrown. The type system cannot catch this because emptiness is not part of the type. Versions that provide safe access and return values in empty states should be used.

Correct

val bos = List[Int]()
println(bos.headOption.getOrElse(0))

Frequently asked questions

What are the prepending and appending operators?

Prepending is written with two colons, and appending is written with a colon and a plus sign. The cost difference between the two is significant: the first runs in constant time, while the second runs in time proportional to the length of the list.

Isn't an immutable collection slow?

Generally no, because structural sharing is used: the new list does not copy the old elements, it points to them. However, choosing the wrong operator or repeatedly copying inside a loop will indeed slow things down.

Should I use List or Vector?

If you will process sequentially from the beginning, List is suitable. If you will perform random access and appending, Vector is noticeably more balanced. Both are immutable and provide the same transformation methods.

Summary

The default list is immutable.

Prepending is cheap, appending is expensive.

Out-of-bounds access throws an error.

The first element cannot be retrieved from an empty list.

Safe access methods return values.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code