Movatterモバイル変換


[0]ホーム

URL:


Open In App

Given a list of integers, the task is to identify and print all elements that appear more than once in the list. For Example: Input:[1, 2, 3, 1, 2, 4, 5, 6, 5], Output:[1, 2, 5]. Below are several methods to print duplicates from a list in Python.

Using Collections.Counter

Counter class from the collections module provides a way to count occurrences and easily identify duplicates.

Python
fromcollectionsimportCountera=[1,2,3,1,2,4,5,6,5]count=Counter(a)res=[numfornum,freqincount.items()iffreq>1]print(res)

Output
[1, 2, 5]

Explanation:

  • Counter(a) counts how many times each number appears.
  • list comprehension extracts only the elements with frequency greater than 1.

Using Set

A set in Python stores only unique elements. By tracking seen elements in a set, duplicates can be identified efficiently.

Python
a=[1,2,3,1,2,4,5,6,5]s=set()dup=[]fornina:ifnins:dup.append(n)else:s.add(n)print(dup)

Output
[1, 2, 5]

Explanation:

  • s keeps track of the elements that have already appeared.
  • If an element n is already in s, it’s added to dup as a duplicate.

Using a Dictionary

A dictionary can be used to count the occurrences of each element. Any element with a count greater than 1 is a duplicate.

Python
a=[1,2,3,1,2,4,5,6,5]count={}fornina:count[n]=count.get(n,0)+1duplicates=[nforn,cincount.items()ifc>1]print(duplicates)

Output
[1, 2, 5]

Explanation:

  • count.get(n, 0) + 1: updates each element’s frequency.
  • The list comprehension selects elements with a count greater than 1.

Using Nested Loops

This method compares every element with all others to find duplicates. It’s easy to understand but less efficient for larger lists.

Python
a=[1,2,3,1,2,4,5,6,5]dup=[]foriinrange(len(a)):forjinrange(i+1,len(a)):ifa[i]==a[j]anda[i]notindup:dup.append(a[i])print(dup)

Output
[1, 2, 5]

Explanation:

  • if a[i] == a[j] and a[i] not in dup: Checks if the element is a duplicate and not already added.
  • dup.append(a[i]): Adds the duplicate element to the list.

Related Articles:


Improve
Improve
Article Tags :

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp