How do you remove duplicates from a comma separated string in python?

You actually haven't specified what you want well enough. As everyone has pointed out, does order matter? Do you want to remove all duplicates, or only strings of the same one?

If order doesn't matter, all of the set solutions are fine. If it does, there are itertools recipes for these cases:

from itertools import ifilterfalse, imap, groupby
from operator import itemgetter

def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in ifilterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

def unique_justseen(iterable, key=None):
    "List unique elements, preserving order. Remember only the element just seen."
    # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
    # unique_justseen('ABBCcAD', str.lower) --> A B C A D
    return imap(next, imap(itemgetter(1), groupby(iterable, key)))

You can apply either of these to 'a,a,b'.split(','):

In [6]: ','.join(set('a,a,b'.split(',')))
Out[6]: 'a,b'

In [7]: ','.join(unique_justseen('a,a,b'.split(',')))
Out[7]: 'a,b'

In [8]: ','.join(unique_everseen('a,a,b'.split(',')))
Out[8]: 'a,b'

or, for a case where they are different:

In [9]: ','.join(set('a,a,b,a'.split(',')))
Out[9]: 'a,b'

In [10]: ','.join(unique_everseen('a,a,b,a'.split(',')))
Out[10]: 'a,b'

In [11]: ','.join(unique_justseen('a,a,b,a'.split(',')))
Out[11]: 'a,b,a'

Python is an object-oriented, high-level programming language with dynamic semantics that is interpreted. Its high-level built-in data structures, combined with dynamic typing and dynamic binding, make it very appealing for Rapid Application Development, as well as use as a scripting or glue language to connect existing components. 

Python's simple, easy-to-learn syntax prioritizes readability, lowering the cost of programme maintenance. Python provides support for modules and packages, which promotes programme modularity and code reuse. The Python interpreter and extensive standard library are free to use and distribute in source or binary form for all major platforms.

In this article, we'll look at what a list is in Python. Since a Python list is a collection of multiple elements, including duplicates, it is sometimes necessary to make the list unique. In this section, we will look at the various methods for removing duplicates from a list in Python. Firstly, let us know what exactly is a list? 

How to Remove Duplicates From a Python list?

In Python, there are numerous methods for removing duplicates from a list. To remove duplicates from a given list, you can make use of these methods and get your work done. Let's take a look at them: 

Method 1 - Naive Method 

To remove duplicates from a list in Python, iterate through the elements of the list and store the first occurrence of an element in a temporary list while ignoring any other occurrences of that element.

The basic approach is implemented in the naive method by:

  • Using a For-loop to traverse the list
  • If the elements do not already exist in a temporary list, they are added to it
  • The temporary list has been assigned to the main list

Example: 

# removing duplicates from the list using naive methods 

# initializing list 

sam_list = [11, 13, 15, 16, 13, 15, 16, 11] 

print ("The list is: " + str(sam_list)) 

# remove duplicates from list

result = [] 

for i in sam_list: 

if i not in result: 

result.append(i) 

# printing list after removal 

print ("The list after removing duplicates : " + str(result))

Output: 

 The list is: [11, 13, 15, 16, 13, 15, 16, 11]

 The list after removing duplicates: [11, 13, 15, 16]

Method 2 - Using List Comprehension

Instead of using the For-loop to implement the Naive method of removing duplicates from a list, we can use Python's List comprehension functionality to do so in just one line of code.

Example:

# removing duplicates from the list using list comprehension 

# initializing list 

sam_list = [11, 13, 15, 16, 13, 15, 16, 11] 

print ("The list is: " + str(sam_list)) 

# to remove duplicates from list 

result = [] 

[result.append(x) for x in sam_list if x not in result] 

# printing list after removal 

print ("The list after removing duplicates: " + str(result))

Output:

The list is: [11, 13, 15, 16, 13, 15, 16, 11]

The list after removing duplicates: [11, 13, 15, 16]

Method 3 - Using set()

This is the most commonly used method for removing a duplicate from a Python list. This is due to the fact that duplicates are not permitted in the set data structure. However, the order of the elements is lost when using this method.

Example: 

# removing duplicates from the list using set() 

# initializing list 

sam_list = [11, 15, 13, 16, 13, 15, 16, 11] 

print ("The list is: " + str(sam_list)) 

# to remove duplicates from list 

sam_list = list(set(sam_list)) 

# printing list after removal 

# ordering distorted

print ("The list after removing duplicates: " + str(sam_list))

Output:

The list is: [11, 15, 13, 16, 13, 15, 16, 11]

The list after removing duplicates: [16, 11, 13, 15]

Method 4 - Using list comprehension + enumerate ()

We find the distinct elements and store them in a temporary list using the List comprehension method. When we use the List comprehension in conjunction with the enumerate() function, the programme checks for previously encountered elements and skips adding them to the temporary list. The enumerate function takes an iterable as an argument and returns it as an enumerating object (index, element), which adds a counter to each iterable element.

Example:

# removing duplicates from the list using list comprehension + enumerate() 

# initializing list 

sam_list = [11, 15, 13, 16, 13, 15, 16, 11] 

print ("The list is: " + str(sam_list)) 

# to remove duplicates from list 

result = [i for n, i in enumerate(sam_list) if i not in sam_list[:n]] 

# printing list after removal 

print ("The list after removing duplicates: " + str(result))

Output:

The list is: [11, 13, 15, 16, 13, 15, 16, 11]

The list after removing duplicates: [11, 13, 15, 16]

Method 5 - Using collections.OrderedDict.fromkeys()

This is the quickest way to accomplish the goal of removing duplicates from the Python list. This method first removes duplicates before returning a dictionary that has been converted to a list. In addition, this method works well with strings.

Example:

# removing duplicates from list using collections.OrderedDict.fromkeys() 

from collections import OrderedDict 

# initializing list 

sam_list = [11, 15, 13, 16, 13, 15, 16, 11] 

print ("The list is: " + str(sam_list)) 

# to remove duplicates from list 

result = list(OrderedDict.fromkeys(sam_list)) 

# printing list after removal 

print ("The list after removing duplicates: " + str(result))

Output:

The list is: [11, 15, 13, 16, 13, 15, 16, 11]

The list after removing duplicates: [11, 15, 13, 16]

Learn data operations in Python, strings, conditional statements, error handling, and the commonly used Python web framework Django. Check out Simplilearn's Python Training course.

How do you remove duplicates from a comma separated string?

We can remove duplicates from a string in the following three steps: Convert comma separated string to an array; Use array_unique() to remove duplicates; Convert the array back to a comma separated string.

How do you remove duplicates from a string in Python?

Given a string S, the task is to remove all the duplicates in the given string..
Sort the elements..
Now in a loop, remove duplicates by comparing the current character with previous character..
Remove extra characters at the end of the resultant string..

What is the easiest way to remove duplicates in Python?

5 Ways to Remove Duplicates from a List in Python.
Method 1: Naïve Method..
Method 2: Using a list comprehensive..
Method 3: Using set().
Method 4: Using list comprehensive + enumerate().
Method 5: Using collections. OrderedDict. fromkeys().

How do you remove duplicates in Python with combination?

How to Remove Duplicates From a Python list?.
Method 1 - Naive Method. ... .
Method 2 - Using List Comprehension. ... .
Method 3 - Using set() ... .
Method 4 - Using list comprehension + enumerate () ... .
Method 5 - Using collections..