Post

PythonPython

S
Swetha Shetty

Posted on 20th April 2024|29 views

0
votes

Python Find Duplicates In List

How to check if there are any duplicates in a python list?

Answers
P
cayrel rings

Posted on 20th April 2024

Now let us check if there are any duplicates in this list below

Lostofelements = ['ok', 'good', 'better', 'good', 'excellent', 'ok']

We can check for duplicates by the below steps

  1. Firstly add list contents into a set
  2. Compare the size of the list and the set

Example:

First, we create a function which follows the before mentioned algorithm

def checkDuplicates_1(listOfElems):

   ''' Check if given list have any duplicates '''

   if len(listOfElems) == len(set(listOfElems)):

       return False

   else:

       return True

Then in the second step lest us check for the duplicates 

 

listOfElems = [‘ok’, ‘good’, ‘better’, ‘good’, ‘excellent’, ‘ok’]

result = checkIfDuplicates_1(listOfElems)

if result:

   print('Yes, list have duplicates')

else:

   print('there are no duplicates in the list')   

Output: Yes, list have duplicates

Write your answer

STILL GOT QUERIES?

Get a Live FREE Demo
  • Explore the trending and niche courses and learning maps
  • Learn about tuition fee, payment plans, and scholarships
  • Get access to webinars and self-paced learning videos