Python | Remove random element from list
Last Updated :
13 Apr, 2023
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()
Python3
import random
test_list = [ 6 , 4 , 8 , 9 , 10 ]
print ( "The original list : " + str (test_list))
test_list.pop(random.randrange( len (test_list)))
print ( "List after removal of random number : " + str (test_list))
|
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.
Python3
import random
test_list = [ 6 , 4 , 8 , 9 , 10 ]
print ( "The original list : " + str (test_list))
random_element = random.choice(test_list)
test_list.remove(random_element)
print ( "List after removal of random number : " + str (test_list))
|
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():
Python3
import random
test_list = [ 6 , 4 , 8 , 9 , 10 ]
print ( "The original list : " + str (test_list))
random_element = random.choice(test_list)
test_list = list ( filter ( lambda x: x ! = random_element, test_list))
print ( "List after removal of random number : " + str (test_list))
|
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
Python3
import random
test_list = [ 6 , 4 , 8 , 9 , 10 ]
random_element = random.choice(test_list)
print ( "The original list : " + str (test_list))
del test_list[test_list.index(random_element)]
print ( "List after removal of random number :" , test_list)
|
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)
Share your thoughts in the comments
Please Login to comment...