Removing duplicates in lists

0 votes

I want to write a program to check if a list has any duplicates and if it does it removes them and returns a new list with the items that weren't duplicated/removed. The code is as follows:

def remove_duplicates():
    t = ['a', 'b', 'c', 'd']
    t2 = ['a', 'c', 'd']
    for t in t2:
        t.append(t.remove())
    return t

Feb 10, 2022 in Python by Dev
• 6,000 points
470 views

1 answer to this question.

0 votes

To remove duplicates from List use, set as set does not contain duplicates and also is unordered.

For Example:

Example = ['a','b','c','d','a','a','b','c','d']

list(set(Example)) 

Output:

['b', 'd', 'c', 'a']
from collections import OrderedDict
OrderedDict((u, True) for u in Example).keys()

Output:

odict_keys(['a', 'b', 'c', 'd'])

Here, OrderedDict remembers the insertion order of keys, and does not change it when a value at a particular key is updated. We use True as one value was needed to unpack the list, which is shown below without using True.

from collections import OrderedDict
OrderedDict((u) for u in Example).keys()

Output

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-ce40dd697e48> in <module>
      1 from collections import OrderedDict
----> 2 OrderedDict((u) for u in Example).keys()

ValueError: need more than 1 value to unpack
answered Feb 10, 2022 by Nandini
• 5,480 points

Related Questions In Python

0 votes
2 answers
0 votes
1 answer

How can I iterate through two lists in Parallel

You have to use the zip function ...READ MORE

answered Apr 17, 2018 in Python by anonymous
1,209 views
0 votes
1 answer

Copying lists in python

Assigning one list to another one simply ...READ MORE

answered Apr 30, 2018 in Python by Nietzsche's daemon
• 4,260 points
448 views
0 votes
1 answer

Difference between two lists in python

difference = list(set(list1) - set(list2)) READ MORE

answered May 24, 2018 in Python by Nietzsche's daemon
• 4,260 points
2,588 views
0 votes
1 answer

Removing duplicates in lists

1)To get rid of duplicate items, convert ...READ MORE

answered Feb 16, 2023 in Python by Rishu
• 300 points
692 views
0 votes
0 answers
0 votes
2 answers
0 votes
1 answer

Is there a label/goto in Python?

Since Python is a structured programming language, ...READ MORE

answered Feb 4, 2022 in Python by Nandini
• 5,480 points
369 views
0 votes
1 answer

What is the use of "assert" in Python?

The statement assert exists in almost every programming ...READ MORE

answered Feb 7, 2022 in Python by Nandini
• 5,480 points
356 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP