Step 1: Select a random element from the list.
element_to_delete = random.choice(my_list)
Step 2: Delete the selected element.
my_list.remove(element_to_delete)
Find the below working application.
delete_random_item_from_list.py
import random
def delete_random_element(my_list):
element_to_delete = random.choice(my_list)
my_list.remove(element_to_delete)
return element_to_delete
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]
print('deleted element : ', delete_random_element(primes))
print('primes : ', primes)
print('\ndeleted element : ', delete_random_element(primes))
print('primes : ', primes)
print('\ndeleted element : ', delete_random_element(primes))
print('primes : ', primes)
Output
deleted element : 17 primes : [2, 3, 5, 7, 11, 13, 19, 23] deleted element : 13 primes : [2, 3, 5, 7, 11, 19, 23] deleted element : 23 primes : [2, 3, 5, 7, 11, 19]
No comments:
Post a Comment