from random import randint def select(lst,i): lst = lst.copy() def partition(a,b): pivot = lst[a] while apivot: b-=1 if a=b: return lst[a] # randomized select n = randint(a,b) lst[a],lst[n] = lst[n],lst[a] pos = partition(a,b) if pos>i: return _select(a,pos-1) elif pos