Answers for "python remove n random elements from a list"

1

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']
Posted by: Guest on October-04-2020

Code answers related to "python remove n random elements from a list"

Python Answers by Framework

Browse Popular Code Answers by Language