Python | Remove random element from list

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()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Remove random element from list
# Using randrange() + pop()
import random
  
# initializing list 
test_list = [6, 4, 8, 9, 10]
  
# printing list 
print("The original list : " + str(test_list))
  
# Remove random element from list
# Using randrange() + pop()
test_list.pop(random.randrange(len(test_list)))
  
# Printing result
print("List after removal of random number : " + str(test_list))

chevron_right


Output :

 
The original list : [6, 4, 8, 9, 10]
List after removal of random number : [6, 4, 8, 10]
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.