How to Remove Duplicates from List in Python

0 min read 142 words

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))

Option 2:

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

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

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])
        
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags