Delete an Item from a list in Python

To delete an item from a list in Python we can use remove() method and del keyword. Here we will learn how to remove or delete an item from a list in Python with some easy example.

Delete an item from a list in Python with examples

We can delete an item from a list –

  • By Index
  • By Value

Let’s create our list first:



my_list = ['hello','hi','codespeedy','you','python','sanake']
print(my_list)

Now we have to delete an item from this list.

At first, we gonna delete an item from this list by its index

The index of a list starts with zero. We gonna delete an element whose index is 3. ( that is you lol )

To delete an item from a list by its index in Python we have to use del keyword

In Python, everything we use is an object and del can delete objects. Thus we can also say that del keyword can be used to delete variables, objects, list or part of a list whatever we want.

my_list = ['hello','hi','codespeedy','you','python','snake']
print('previous list---',my_list)
del my_list[3]
print('final list---',my_list)

Output:

previous list--- ['hello', 'hi', 'codespeedy', 'you', 'python', 'snake']
final list--- ['hello', 'hi', 'codespeedy', 'python', 'snake']

Process finished with exit code 0

Here We have deleted an item by its index.

Now we will delete an element from a list in Python by its value

Now, we have to delete an element whose value is ‘snake’

In order to do this, we gonna use remove() method.

Just put the value of the element in the parameter, you want to be deleted.

my_list = ['hello','hi','codespeedy','you','python','snake']
print('previous list---',my_list)
my_list.remove('snake')
print('final list---',my_list)

Output:

previous list--- ['hello', 'hi', 'codespeedy', 'you', 'python', 'snake']
final list--- ['hello', 'hi', 'codespeedy', 'you', 'python']

Process finished with exit code 0

You may also learn,

Leave a Reply

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