python remove n random elements from a list

Solutions on MaxInterview for python remove n random elements from a list by the best coders in the world

showing results for - "python remove n random elements from a list"
Alina
04 Sep 2019
1# Formula to delete n random elements from a list:
2import random
3def delete_random_elems(input_list, n):
4    to_delete = set(random.sample(range(len(input_list)), n))
5    return [x for i,x in enumerate(input_list) if not i in to_delete]
6
7# Note, this function doesn't take a seed value, so it will be different
8# 	every time you run it. 
9  
10# Example usage:
11your_list = ['so', 'many', 'words', 'I', 'want', 'to', 'sample']
12delete_rand_items(your_list, 3) # Randomly delete 3 elements from the list
13--> ['so', 'many', 'want', 'sample']