Delete random item from a list in Python

This Python tutorial will focus on How to delete random item from a list in Python. We will show you an easy way to pick a random item from a list and remove random item or element from a list in Python.

So, let’s start with an example of a list.

my_list = ['bird', 'fish', 'insect', 'reptile', 'mammal']

Here is a list with 5 items in it. It does not matter how many items are there in your list.

We will use random module here.

Go through this tutorial: Python | Select a random item from a list in Python

Remove a random element from a list in Python

We will follow these steps:

Python program to delete a random item from list:

import random
my_list = ['bird', 'fish', 'insect', 'reptile', 'mammal']
random_item_from_list = random.choice(my_list)
my_list.remove(random_item_from_list)
print(my_list)

Output:



['bird', 'fish', 'reptile', 'mammal']

As you can see in the above output, one random item is removed from the list.

Each time you will run this program a random item will be removed.

Remove all items from a list randomly one by one in Python

import random
my_list = ['bird', 'fish', 'insect', 'reptile', 'mammal']
for i in range(0,len(my_list)):
    my_list.remove(random.choice(my_list))
    print(my_list)

Output:

['bird', 'insect', 'reptile', 'mammal']
['bird', 'insect', 'mammal']
['insect', 'mammal']
['insect']
[]

Conclusion:

You can use this technique to create fun games in Python.

The random module is very much useful to create a lot of fun games. Here are some examples:

Leave a Reply

Your email address will not be published. Required fields are marked *