Main Content

Shuffling a list - Ruby and Python

Archive - Originally posted on "The Horse's Mouth" - 2014-12-28 01:53:20 - Graham Ellis

Shuffling a list / array is quite a common requirement. The best way to do it is to take a list of all the items to be shuffled, and to choose one at random as the first member of the output list / array. Then move the last item on the incoming array into the gap left, and choose another from the now shorter incoming array to add to the shuffled array. Keep going until the incoming list is empty.

Newcomers to coding may simply start by choosing incoming elements at random, but without the moving up of the remaining elements (housekeeping) they rapidly find themselves selecting some of the incoming items multiple times while missing out others, or in a loop of select and reject as they keep sampling and saying "no, we've had that one already".

A number of years ago, I wrote a shuffling program in Python as a demonstration of list manipulation - and also to help my son Chris and his (then) Girlfriend Delene play the tracks on their computer in a random order. The code is [here]. If you want to tell a story against someone, tell it against yourself - and so I do on courses, for I should have looked closer at Python as it has a built in shuffle method and much of my code was needless - there's a much shorter answer [here].

Years later, I had 72 images, sequentially numbered, that I wanted to mix up and rename, and as the course I'm starting the new year with is Ruby Programmng, I've elected to write the code in that language. Code [here].

The langauges turn out to be remarkably similar

Python shuffle code:

  shuffle = []
  while len(basehand):
    posn = int(random()*len(basehand))
    shuffle.append(basehand[posn])
    basehand[posn] = basehand[-1]
    basehand.pop()


Ruby shuffle code:

  shuffled = []
  while pix.length > 0 do
    position = rand() * pix.length
    shuffled.push(pix[position])
    pix[position] = pix[-1]
    pix.pop()
  end