SoFunction
Updated on 2024-11-18

Python implementation of determining if a given list has duplicate elements

This article example describes the Python implementation of determining whether a given list has duplicate elements. Shared for your reference, as follows:

The topic is very simple, just a brief refresher on a method, most_common, which is a method of the Counter class in the collection module, and the specific method usage can be found in the

Here is a simple implementation:

#!usr/bin/env python
#encoding:utf-8
'''''
__Author__:Yishui Cold City
Function: Given a list determine if there are any duplicate elements in it.
'''
from collections import Counter
def func1(num_list):
  '''''
  Use the set method directly
  '''
  if len(num_list)!=len(set(num_list)):
    print 'have duplicates!!!'
  else:
    print 'no duplicates!!'
def func2(num_list):
  '''''
  Using the Counter class with collections
  '''
  cou=Counter(num_list)
  first=cou.most_common(1)
  if first[0][1]>1:
    print 'have duplicates!!!'
  else:
    print 'no duplicates!!'
if __name__ == '__main__':
  num_list=[[1,2,3,4],[6,7,8],[4,5,6,6,6]]
  print 'I test results:'
  for one_list in num_list:
    print 'one_list', one_list
    func1(one_list)
    func2(one_list)

The results are as follows:

PS: Here we recommend 2 more very convenient statistical tools for your reference:

Online word count tool:
http://tools./code/zishutongji

Online character counting and editing tool:
http://tools./code/char_tongji

Readers interested in more Python related content can check out this site's topic: theSummary of Python file and directory manipulation techniques》、《Summary of Python text file manipulation techniques》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniquesand thePython introductory and advanced classic tutorials

I hope that what I have said in this article will help you in Python programming.