Created
March 12, 2011 05:36
-
-
Save amcameron/867064 to your computer and use it in GitHub Desktop.
remove duplicates in a list, using recursion instead of loops.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def remdup(l, dup=None): | |
| # If has zero or one elements, there are no duplicates. | |
| if len(l) < 2: | |
| return l | |
| # If there's a duplicate to remove, remove it and recurse until ValueError | |
| # is raised, which means there are none left to remove. Since lists are | |
| # mutable, we don't have to capture this. | |
| if dup is not None: | |
| try: | |
| l.remove(dup) | |
| remdup(l, dup) | |
| except ValueError: | |
| pass | |
| # No more duplicates to remove? Then recurse, removing duplicates of the | |
| # current head! | |
| return [l[0]] + remdup(l[1:], l[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment