How to shuffle (randomize) a list in Scala (List, Vector, Seq, String)

As a quick note today, to shuffle/randomize lists and sequences in Scala, use this technique:

val newList = scala.util.Random.shuffle(List(1, 2, 3, 4))

Remember that types like List, Seq, and Vector are immutable, so you need to assign the shuffle result to a new variable, as shown.

More list shuffling examples

Here’s what this approach looks like in the Scala REPL:

import scala.util.Random

scala> val x = Random.shuffle(List(1,2,3,4))
x: List[Int] = List(2, 3, 1, 4)

scala> val x = Random.shuffle(List(1,2,3,4))
x: List[Int] = List(3, 4, 2, 1)

scala> val x = Random.shuffle(List(1,2,3,4))
x: List[Int] = List(1, 3, 4, 2)

You can also create a Random instance and call shuffle on it:

scala> val r = scala.util.Random
r: util.Random.type = scala.util.Random$@4715ae33

scala> val x = r.shuffle(List(1,2,3,4))
x: List[Int] = List(4, 2, 1, 3)

scala> val x = r.shuffle(List(1,2,3,4))
x: List[Int] = List(1, 4, 2, 3)

As mentioned, a key in this solution is to know that shuffle doesn’t randomize the List it’s given; instead it returns a new List that has been randomized (shuffled). This is consistent with functional programming principles, where you don’t modify the thing you are given, you return a modified version of it.

As a final note, you can use other Scala sequences with Random.shuffle like Seq and Vector. In fact, because a Scala string can be treated like a list, you can also randomize/shuffle a string, as shown in this Scala 3 REPL example:

scala> Random.shuffle("emily")
val res0: scala.collection.immutable.WrappedString = miley

A Scala coin flip or “heads or tails” method

In a related note, this code shows how you can write a Scala “coin flip” or “heads or tails” method:

import scala.util.Random
def headsOrTails() = Random.shuffle(List(true,false)).head

That code:

  • Creates a list containing only true and false
  • It shuffles that list
  • Then it returns the first items in the shuffled list