How to remove items or duplicates from a list in Python. Don't run around in loops to edit lists if there are built-in functions to help you out.

  • Remove duplicates from a list
  • Remove elements from a list
  • Clear a list

Our list:

my_list = [1,1,1,1,2,3,4]

Remove duplicates from a list

Sets quickly kill duplicates. Remember to convert it back to a list.

my_list = list(set(my_list))

Remove elements from a list

remove() or pop() will remove elements from a list. pop() returns the value you remove.

my_list.remove(1) #note that this will only remove the first instance of 1.
use_number_later = my_list.pop() #default removes last item in list. Add index to pop another. (my_list.pop(0))

Clear a list

This is easy as lists in Python come with a method called clear().

my_list.clear()
print(my_list)
> []

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store