Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

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']
Comment

PREVIOUS NEXT
Code Example
Python :: sort value_counts output 
Python :: Basic method of Converting List to Dataframe 
Python :: how to read files in python 
Python :: python colorama example 
Python :: max of matrix numpy 
Python :: simple jwt django 
Python :: how to invert a list in python 
Python :: merge multiple csv files 
Python :: username nextcord interactions 
Python :: difference between sort and sorted 
Python :: sin and cos in python 
Python :: reload function jupyter notebook 
Python :: Iterate through python string starting at index 
Python :: get columns containing string 
Python :: python type hint for a string 
Python :: pandas datetime.time 
Python :: pandas strips spaces in dataframe 
Python :: get last day of month python 
Python :: python create virtualenv 
Python :: list to excel python 
Python :: datetime year python 
Python :: how to find no of times a elements in list python 
Python :: python sorted lambda 
Python :: python live video streaming flask 
Python :: get all files in directory python 
Python :: discord.py check if message has certain reaction 
Python :: python get current time 
Python :: horizontal bar plot python 
Python :: Creating a list with list comprehensions 
Python :: python string math 
ADD CONTENT
Topic
Content
Source link
Name
5+1 =