"IndexError: list index out of range" when trying to read values from an appended list

OS: macOS Big Sur 11.5.2
Psychopy standalone version: 2022.2.2

I’m adapting an n-back task published by Rebecca Hirst on this site. My goal is to include three different conditions in this task (i.e., 0-back, 1-back, and 2-back conditions) to randomly present numbers 0-9. There are 20 trials for each condition (15 non-n-back trials and 5 n-back trials), and each condition is presented in one block separately. The 0-back condition works but there is an error message popped up when I ran the 1-back condition.

My files have been attached and the following code is what I modified from the original code in the Begin Routing tab for the 1-back condition:

thisTrialType = p1TrialList[trialCount]
thisNumber = "0"
corrAns = '0'
numberSet = p12AllNumbers

if thisTrialType == 0: # not an 1-back trial
    if len(p1NumbersShown) > p1n: # do not select the number n-back
    thisNumber = numberSet[-1]
    corrAns = 'None'
elif thisTrialType == 1: # an 1-back trial
    thisNumber = p1NumbersShown[-p1n]
    corrAns = 'l'

thisExp.addData('cond', 'p1')
thisExp.addData('trialCount', trialCount)
thisExp.addData('itemPresented', thisNumber)
thisExp.addData('trialType', thisTrialType)
thisExp.addData('corrAns', corrAns)

However, I got the following error message:

File "/Users/chiachuanyu/My Drive/Psychopy/Dissertation/nBack/nBack_lastrun.py", line 787, in <module>
    thisNumber = numberSet[-1]
IndexError: list index out of range

I’m not familier with Python coding and I’ve tried several ways to sole this problem. There are two ways partly solve this issue:

  1. In the Begin Experiment code, put
    p12AllNumbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    rather than
    p12AllNumbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].
    But this would result in consecutively repeated numbers in both n-back and non-n-back trials.

  2. In the Begin Experiment code in the routine named p0Ins, set totalTrials = 10 and nBackTrials = 4 rather than totalTrials = 20 and nBackTrials = 5.
    But this is not what I want for the task.

Could anyone helps?

My kindest regards to everyone,

nback_lastrun.py (48.9 KB)
nBack.psyexp (52.8 KB)
nBack.py (49.0 KB)
tBlockList.xlsx (8.8 KB)

This issue has been solved. I’ll upload the latest version of my modification later.