'Filling an empty sequence after clearing

I have written code to determine the average number of recursive calls made to a function quickselect, and while my quickselect code works and my main function works if I only have one trial, I am unable to run any successive trials. I am getting the IndexError cannot choose from an empty sequence. I have tried moving hold.clear() to different locations in the loop but it is not repopulating no matter where I put it. Any suggestions would be welcomed.

import numpy
import numpy as np
import random

def main(trials,k):
    i = 0;
    hold = []
    calls = -1;
    while i < trials:
        print(hold)
        hold.clear()
        generate(hold, k)
        print(hold)
        quickselect(hold, k, calls)
        i = i + 1
    print(calls/trials)


def generate(l,n):
    for i in range(n):
        r=random.randint(0,n)
        if r not in l:
            l.append(r)


def quickselect(l, k, calls) :
    
    
    calls = calls + 1
    length = len(l)
    
    
    pivot = random.choice(l)
    
    l_small = []
    l_big = []

    smalltrack = 0
    bigtrack = 0
    i = 0
    ispivot = 0
    while i < length:
        
        compare = l[i]
        if compare < pivot:
            l_small.append(compare)
            smalltrack = smalltrack + 1
            
        elif l[i] > pivot:
            l_big.append(compare)
            bigtrack = bigtrack + 1
        else:
            ispivot = ispivot + 1
            
        i = i + 1
    
    checker = len(l_small) + len(l_big)
    
    checker = checker + ispivot
    
    assert(length == checker)
    


    if k <= len(l_big):
        
    # kth largest must be in l_big
    
        res = quickselect(l_big, k, calls)
        
        return res
    elif k > len(l_big) + 1:
        
    # kth largest must be in l_small
    
        res = quickselect(l_small, k - len(l_big) - 1, calls)
        
        return res
    else:
        
        print(calls)
        return calls


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source