Open In App

Python | Remove random element from list

Last Updated : 13 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with Python lists, we can have a problem or part of it, in which we desire to convert a list after deletion of some random element. This can have it's application in gaming domain or personal projects. Let's discuss certain way in which this task can be done. 

Method : Using randrange() + pop() In this, we just combine the functionality of above functions into one and achieve this task. The random element is chosen by randrange() and then is accessed and removed from the list using pop() 


Output
The original list : [6, 4, 8, 9, 10]
List after removal of random number : [6, 4, 8, 9]

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Another approach to remove a random element from a list in Python is using the random.choice() method. This method returns a random element from a given list. After getting the random element, it can be removed from the list using the list.remove() method.


Output
The original list : [6, 4, 8, 9, 10]
List after removal of random number : [4, 8, 9, 10]

Time complexity: O(n)
Auxiliary Space: O(1)

Method : Using filter () and lambda(): 


Output
The original list : [6, 4, 8, 9, 10]
List after removal of random number : [4, 8, 9, 10]

Time complexity: O(n)
Auxiliary Space: O(n-1) 

Method : Using del keyword


Output
The original list : [6, 4, 8, 9, 10]
List after removal of random number : [6, 4, 8, 9]

Time complexity: O(n)
Auxiliary Space: O(1) 


Practice Tags :

Similar Reads