psychopy.org | Reference | Downloads | Github

IndexError: list index out of range in each frame custom code

Dear experts,

I currently encountered a strange error that can’t be resolved.

I am using v2021.2.3.

In each frame, I append a value to the a list. I want to find out the first time an element in the list larger than 0.03, and give this number to a variable. I am be able to print out the output. But when I assign the value to a variable psychopy showed me the error:

idx_joymax = li.index(list(filter(lambda i: i > 0.03, li))[0])
IndexError: list index out of range

Below is my code in the each frame tab:

li.append(joystick_prac_2.getY())
if joy_min >= -0.02 and joy_max <= 0.03:
    idx_joymax = 0 
    idx_joymin = 0
else: 
    # using filter() + lambda to find index of 
    #first element just greater than 0.03
    print("li")
    print(li)
    print("the first number")
    print(list(filter(lambda i: i > 0.03, li))[0])
    print("the first number index")
    print(li.index(list(filter(lambda i: i > 0.03, li))[0])) 
    idx_joymax = li.index(list(filter(lambda i: i > 0.03, li))[0])

I got the all the output corrected for the print out values. But the line idx_joymax = li.index(list(filter(lambda i: i > 0.03, li))[0]) throw me an error.

Thanks in advance.

Hi Catherine,

Could you include the content of li at the moment it gives the error? I have been playing around with your code and the only way in which I can reproduce the IndexError for now is when li does not contain a value for which the expression i > 0.03 holds.

Alternatively, if you are adding the values on each frame, can’t you do something like this?

if joy_min >= -0.02 and joy_max <= 0.03:
    idx_joymax = 0 
    idx_joymin = 0
elif joy_max > 0.03: 
    idx_joymax = len(li) - 1 # Because that's the last element that was added to the list?