How to Remove Duplicates from List in Python

The challenge

Define a function that removes duplicates from an array of numbers and returns it as a result.

The order of the sequence has to stay the same.

The solution in Python code

Option 1:

def distinct(seq): return list(dict.fromkeys(seq))
Code language: Python (python)

Option 2:

distinct = lambda s: [e for i,e in enumerate(s) if e not in s[:i]]
Code language: Python (python)

Option 3:

def distinct(seq): result = [] seen = set() for a in seq: if a not in seen: result.append(a) seen.add(a) return result
Code language: Python (python)

Test cases to validate our solution

import test from solution import distinct @test.describe("Fixed Tests") def fixed_tests(): @test.it('Basic Test Cases') def basic_test_cases(): test.assert_equals(distinct([1]), [1]) test.assert_equals(distinct([1, 2]), [1, 2]) test.assert_equals(distinct([1, 1, 2]), [1, 2]) test.assert_equals(distinct([1, 1, 1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]) test.assert_equals(distinct([1, 2, 2, 3, 3, 4, 4, 5, 6, 7, 7, 7]), [1, 2, 3, 4, 5, 6, 7])
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments