Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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 N minimum elements from list of integers
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 N minimum elements from list of integers

S

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

Similar Reads

  • Program to print N minimum elements from list of integers
    Our task is to extract the smallest N elements from a list of integers. For example, if we have a list [5, 3, 8, 1, 2] and want the smallest 3 elements, the output should be [1, 2, 3]. We’ll explore different methods to achieve this. Using heapq.nsmallestThis method uses the nsmallest() function fro
    2 min read
  • How to Create a List of N-Lists in Python
    In Python, we can have a list of many different kinds, including strings, numbers, and more. Python also allows us to create a nested list, often known as a two-dimensional list, which is a list within a list. Here we will cover different approaches to creating a list of n-lists in Python. The diffe
    3 min read
  • 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. [GFGTABS] Python
    2 min read
  • Remove All Duplicates from a Given String in Python
    The task of removing all duplicates from a given string in Python involves retaining only the first occurrence of each character while preserving the original order. Given an input string, the goal is to eliminate repeated characters and return a new string with unique characters. For example, with
    2 min read
  • Converting all Strings in a List to Integers - Python
    We are given a list of strings containing numbers and our task is to convert these strings into integers. For example, if the input list is ["1", "2", "3"] the output should be [1, 2, 3]. Note: If our list contains elements that cannot be converted into integers such as alphabetic characters, string
    2 min read
  • Check if a List is Sorted or not - Python
    We are given a list of numbers and our task is to check whether the list is sorted in increasing or decreasing order. For example, if the input is [1, 2, 3, 4], the output should be True, but for [3, 1, 2], it should be False. Using all()all() function checks if every pair of consecutive elements in
    3 min read
  • Get a list as input from user in Python
    We often encounter a situation when we need to take a number/string as input from the user. In this article, we will see how to take a list as input from the user using Python. Get list as input Using split() MethodThe input() function can be combined with split() to accept multiple elements in a si
    3 min read
  • Pass a List to a Function in Python
    In Python, we can pass a list to a function, allowing to access or update the list's items. This makes the function more versatile and allows us to work with the list in many ways. Passing list by Reference When we pass a list to a function by reference, it refers to the original list. If we make an
    2 min read
  • Python | Pandas Index.get_duplicates()
    Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.get_duplicates() function extract duplicated index elements. This functio
    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