Removing duplicates in lists

0 votes

How can I determine whether a list contains any duplicates and then produce a fresh list free of them?

Feb 15, 2023 in Python by Arya
• 990 points
913 views

1 answer to this question.

0 votes

1)To get rid of duplicate items, convert the list to a set.
2)Compare the original list's length to the set's length. There are no duplicates in the list if they are the same. Otherwise, there are duplicates on the list.

For ex:

my_list = [1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9]

# check if the list contains duplicates
if len(my_list) != len(set(my_list)):
    # if the list contains duplicates, create a new list without duplicates
    new_list = []
    for item in my_list:
        if item not in new_list:
            new_list.append(item)
else:
    # if the list does not contain duplicates, use the original list
    new_list = my_list

print(new_list) # output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Master the art of Data Science with Python and unlock the power of insights.

answered Feb 16, 2023 by Rishu
• 300 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,369 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
625 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,767 views
0 votes
1 answer

Removing duplicates in lists

To remove duplicates from List use, set ...READ MORE

answered Feb 10, 2022 in Python by Nandini
• 5,480 points
658 views
0 votes
0 answers
0 votes
2 answers
0 votes
1 answer

Relative imports in Python 3

Because the first statement, from.mymodule import myfunction, ...READ MORE

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

Replacements for switch statement in Python?

To get the same function as a ...READ MORE

answered Feb 16, 2023 in Python by Rishu
• 300 points
1,133 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