Skip to content

Instantly share code, notes, and snippets.

@jgarciabu
Last active August 9, 2017 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgarciabu/200d36fbc84ec6a7d30bff74a725671f to your computer and use it in GitHub Desktop.
Save jgarciabu/200d36fbc84ec6a7d30bff74a725671f to your computer and use it in GitHub Desktop.
Ex 14 List Remove Duplicates.py
# -*- coding: utf-8 -*-
"""
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.
Extras:
Write two different functions to do this - one using a loop and constructing a
list, and another using sets.
Go back and do Exercise 5 using sets, and write the solution for that in a
different function.
"""
import random as rd
randlist = []
def build_list():
global randlist
while len(randlist) < 10:
randlist.append(rd.randrange(8))
return randlist
def remove_dupes():
global randlist
nodupes = list(set(randlist))
return nodupes
def only_dupes():
global randlist
newlist = list(set([item for item in randlist if randlist.count(item) > 1]))
return newlist
print("Raw list: {}".format(build_list()))
print("List with duplicates removed: {}".format(remove_dupes()))
print("Duplicated numbers in list: {}".format(only_dupes()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment