Search code examples
pythonpython-3.xlistunique

Remove duplicates from a list in-place


How can one make a list contain only unique items while preserving order AND updating it in-place?

I know that a set can be used, but it will not guarantee ordering.


Solution

  • Use a supporting set, and a while loop:

    def unique(arr):
        tmp_set = set()
        i = 0
        while i < len(arr):
            if arr[i] in tmp_set:
                del arr[i]
            else:
                tmp_set.add(arr[i])
                i += 1
    

    The above will update the array in-place, and preserve ordering of the elements as well.