Uniqify

The Python version is neat in that it's entirely type agnostic as long asthe value supports hashing.I'm sure it's possible to do an equivalent one in Go using interface{}.Patches welcome.

For faster variants in Python seeFastest way to uniqify a list inPython.

For some more thoughts on this, and an example of a implementationthat is not in-place check out this mailing listthread.

Python

  1. def uniqify(seq):
  2. seen = {}
  3. unique = []
  4. for item in seq:
  5. if item not in seen:
  6. seen[item] = 1
  7. unique.append(item)
  8. return unique
  9.  
  10. items = ['B', 'B', 'E', 'Q', 'Q', 'Q']
  11. print uniqify(items) # prints ['B', 'E', 'Q']

Go

  1. package main
  2.  
  3. import "fmt"
  4.  
  5. func uniqify(items *[]string) {
  6. seen := make(map[string]bool)
  7. j := 0
  8. for i, x := range *items {
  9. if !seen[x] {
  10. seen[x] = true
  11. (*items)[j] = (*items)[i]
  12. j++
  13. }
  14. }
  15. *items = (*items)[:j]
  16. }
  17.  
  18. func main() {
  19. items := []string{"B", "B", "E", "Q", "Q", "Q"}
  20. uniqify(&items)
  21. fmt.Println(items) // prints [B E Q]
  22. }