python randomly remove element from list code example
Example: python remove n random elements from a list
# Formula to delete n random elements from a list:
import random
def delete_random_elems(input_list, n):
to_delete = set(random.sample(range(len(input_list)), n))
return [x for i,x in enumerate(input_list) if not i in to_delete]
# Note, this function doesn't take a seed value, so it will be different
# every time you run it.
# Example usage:
your_list = ['so', 'many', 'words', 'I', 'want', 'to', 'sample']
delete_rand_items(your_list, 3) # Randomly delete 3 elements from the list
--> ['so', 'many', 'want', 'sample']