| Reference | Downloads | Github

Randomize trial order without repeating stimuli twice in a row


If this template helps then use it. If not then just delete and start from scratch.

OS : Win10
PsychoPy version : 3.0.5
Standard Standalone? (y/n) : yes

I am running a study where 4 stimuli are presented a number of times per block. Specifically, I have a .csv file with 24 rows, and there are 4 stimuli in one of the columns of the .csv file with each stimulus repeating 6 times. For each block, I need the rows to be randomly selected. However, I also need to make sure each stimulus is never repeated. As an example, the 4 stimuli are: lavender, lilac, lemon, pear. Each should be presented 6 times per block, and in a random order without any stimuli presented twice. For instance, if they see a lemon, the next stimulus must be random, but it cannot be a lemon again. I cannot figure out a code component I could put at the beginning of each block that would achieve this. Any help would be greatly appreciated. Thank you!



This kind of custom randomisation constraint can’t be implemented within Builder’s available options using a conditions file. What you need to do is insert a code component and use custom code to generate a new randomised conditions file (or list of conditions in memory) on each run.

A possible algorithm would be:

  • create a reference list ['lavender', 'lilac', 'lemon', 'pear']
  • copy it.
  • shuffle that copy. This is now the first 4 conditions, in order.
  • copy the reference list again.
  • extract the item from it that is the same as the last item of the first list.
  • randomly sample one of the three remaining items and append it to the first list.
  • put the extracted item back in the second list.
  • shuffle the second list.
  • extend the first list with the second list (which now contains 3 items). The result is now the first 8 conditions in order.
  • repeat the previous 6 steps 4 times.