Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Program to print duplicates from a list of integers in Python
Next article icon

Program to print duplicates from a list of integers in Python

Last Updated : 27 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will explore various methods to print duplicates from a list of integers in Python. The simplest way to do is by using a set.

Using Set

Set in Python only stores unique elements. So, we loop through the list and check if the current element already exist (duplicate) in the set, if true then keep this element to duplicate list. Otherwise, add element to set.

Python
a = [1, 2, 3, 1, 2, 4, 5, 6, 5]  # Initialize an empty set to store seen elements s = set()  # List to store duplicates dup = []  for n in a:     if n in s:         dup.append(n)     else:         s.add(n)  print(dup) 

Output
[1, 2, 5] 

Explanation:

  • The seen set tracks the numbers we've already encountered.
  • If a number is found in seen then it is added to the duplicates list.

Note: This approach is efficient because checking membership in a set is O(1) on average.

Let's explore other different ways to print duplicates from a list of integers:

Table of Content

  • Using Nested Loops (Not Efficient)
  • Using a Dictionary

Using Nested Loops (Not Efficient)

In this approach, we use two nested loops. The outer loop picks an element from the list and the inner loop compares it with every other element to see if it matches. If a match is found then it's considered a duplicate.

Python
a = [1, 2, 3, 1, 2, 4, 5, 6, 5]  # List to store duplicates dup = []  # Compare each element with other elements for i in range(len(a)):     for j in range(i + 1, len(a)):          # If a duplicate is found and not already recorded         if a[i] == a[j] and a[i] not in dup: 			             # Add to duplicates list             dup.append(a[i])   print(dup) 

Output
[1, 2, 5] 

Using a Dictionary

This method uses a dictionary to count how many times each element appears in the list. If an element appears more than once then it is a duplicate.

Python
a = [1, 2, 3, 1, 2, 4, 5, 6, 5]  # Initialize a dictionary to count occurrences d = {}  for n in a:     d[n] = d.get(n, 0) + 1  # Find duplicates by filtering numbers with count > 1 dup = [n for n, c in d.items() if c > 1]  print(dup) 

Output
[1, 2, 5] 

Explanation:

  • The d dictionary counts the occurrences of each number.
  • We then filter out the numbers with a count greater than 1 to find the duplicates.

Note: This approach also has O(n) time complexity due to dictionary operations.


Next Article
Program to print duplicates from a list of integers in Python

S

SaumyaBansal
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

    Program to print all distinct elements of a given integer array in Python | Ordered Dictionary
    Given an integer array, print all distinct elements in array. The given array may contain duplicates and the output should print every element only once. The given array is not sorted. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45} Output: 12, 10, 9, 45, 2 Input: arr[] = {1, 2, 3, 4, 5} Out
    2 min read
    Ways to remove duplicates from list in Python
    In this article, we'll learn several ways to remove duplicates from a list in Python. The simplest way to remove duplicates is by converting a list to a set.Using set()We can use set() to remove duplicates from the list. However, this approach does not preserve the original order.Pythona = [1, 2, 2,
    2 min read
    Output of python program | Set 11(Lists)
    Pre-requisite: List in python 1) What is the output of the following program? Python data = [2, 3, 9] temp = [[x for x in[data]] for x in range(3)] print (temp) a) [[[2, 3, 9]], [[2, 3, 9]], [[2, 3, 9]]] b) [[2, 3, 9], [2, 3, 9], [2, 3, 9]] c) [[[2, 3, 9]], [[2, 3, 9]]] d) None of these Ans. (a) Exp
    3 min read
    Python | Remove consecutive duplicates from list
    Removing consecutive duplicates from a list means eliminating repeated elements that appear next to each other in the list. If an element repeats consecutively, only the first occurrence should remain and the duplicates should be removed.Example:Input: ['a', 'a', 'b', 'b', 'c', 'a', 'a', 'a']Output:
    3 min read
    Find all duplicate characters in string in Python
    In this article, we will explore various methods to find all duplicate characters in string. The simplest approach is by using a loop with dictionary.Using Loop with DictionaryWe can use a for loop to find duplicate characters efficiently. First we count the occurrences of each character by iteratin
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
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