LearnFrenzy
Sign in Take a free test

Strings · Strings Coding Problems · Question 5

Remove duplicate characters keeping the first occurrence in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Remove repeated characters from each string, keeping the first occurrence of each, in order.

Solution
main.py Run
def dedupe(s):
    seen = set()
    result = []
    for ch in s:
        if ch not in seen:
            seen.add(ch)
            result.append(ch)
    return "".join(result)

for s in ["programming", "banana", "aabbcc"]:
    print(s, "->", dedupe(s), "|", "".join(dict.fromkeys(s)))

Output Verified by running it on Python 3

programming -> progamin | progamin
banana -> ban | ban
aabbcc -> abc | abc

A set remembers what has been seen; the list keeps the order. dict.fromkeys(s) is a one-line equivalent because dicts keep insertion order.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links