Practice Python

Beginner Python exercises

15 May 2014

List Remove Duplicates

Exercise 14 (and Solution)

Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates.



Concepts for this week:


In mathematics, a set is a collection of elements where no element is repeated. This becomes useful because if you know your data is stored in a set, you are guaranteed to have unique elements.

Features of sets

In Python

In Python, you make and use a set with the set() keyword. For example:

  names = set()

And the output will be;

  set(['Michele', 'Robin'])

You can do to a set almost anything you can do to a list (except ask for things like “the third element”). See the Python documentation about sets to get a full list of things you can do to sets.

You can convert from a list to a set and a set to a list pretty easily:

  names = ["Michele", "Robin", "Sara", "Michele"]
  names = set(names)
  names = list(names)

And the result of this will be:

  ['Michele', 'Robin', 'Sara']

Happy coding!

Enjoying Practice Python?

Explore Yubico
Explore Yubico
comments powered by Disqus