Get Random Element(s) from a List

Updated Answer

As José Valim said in his answer, in Elixir 1.1 and above, you can now use these methods to get random element(s) from a list:

  • Enum.random/1 – For getting single random element
  • Enum.take_random/2 – For getting multiple random elements

Example:

Enum.random(list)                         #=> 4

Enum.take_random(list, 3)                 #=> [3, 9, 1]
Enum.take_random(list, 1)                 #=> [7]

Remember to call :random.seed(:erlang.now) first!


Original Answer

I’m still unable to find a ‘proper’ and ‘magical’ way to do this, but this is the best I could come up:

For getting a single random element:

list |> Enum.shuffle |> hd
#=> 4

Note: This gives an exception if the list is empty

For getting multiple random elements:

list |> Enum.shuffle |> Enum.take(3)
#=> [7, 1, 5]

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)