I would have used numpy and
np.where
+ np.delete
(it has been fully detailled here after to see how it works); actually only lines 9-11-12-(22) are necessary.import numpy as np # a list is created first using numpy N = 5_000 M = np.random.randint(-2, 10_000, size=(N)).tolist() # it starts here MaxNumber = 4_000 Mat = np.asarray(M) Ind = np.where(Mat >= MaxNumber) n = np.shape(Ind)[1] print(f"There's {n} elements to remove") Mat = np.delete(Mat, np.s_[Ind]) # you can of course sort the array if it's needed Indexes = Mat.argsort() MatSorted = Mat[Indexes] # now you can go back to a list M_new = MatSorted.tolist()