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 in Python by Dev
• 6,000 points
27 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 by Nandini
• 5,480 points

Related Questions In Python

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
599 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
162 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,044 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,821 views
0 votes
1 answer
0 votes
1 answer

Is there a label/goto in Python?

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

answered Feb 4 in Python by Nandini
• 5,480 points
18 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 in Python by Nandini
• 5,480 points
32 views
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP