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:
Count frequencies of all elements in array in Python using collections module
Next article icon

Program to print all distinct elements of a given integer array in Python | Ordered Dictionary

Last Updated : 07 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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} Output: 1, 2, 3, 4, 5  Input: arr[] = {1, 1, 1, 1, 1} Output: 1

This problem has existing solution please refer Print All Distinct Elements of a given integer array link. We will solve this problem in python quickly using Ordered Dictionary. Approach is simple,

  1. Convert array into dictionary data structure using OrderedDict.fromkeys(iterable) function, it converts any iterable into dictionary having elements as Key in the same order they appeared in array.
  2. Now iterate through complete dictionary and print keys.

Python3




# Python program to print All Distinct
# Elements of a given integer array
 
from collections import OrderedDict
 
def printDistinct(input):
     # convert list into ordered dictionary
     ordDict = OrderedDict.fromkeys(input)
 
     # iterate through dictionary and get list of keys
     # list of keys will be resultant distinct elements
     # in array
     result = [ key for (key, value) in ordDict.items() ]
 
     # concatenate list of elements with ', ' and print
     print (', '.join(map(str, result))) 
 
# Driver program
if __name__ == "__main__":
    input = [12, 10, 9, 45, 2, 10, 10, 45]
    printDistinct(input)
 
 

Output:

12, 10, 9, 45, 2

Approach#2: 

The approach of this program is to use a set to keep track of the distinct elements while iterating through the input array. Whenever a new element is encountered, it is printed and added to the set. This ensures that only the distinct elements are printed.

Algorithm

Create a set to store distinct elements.
Traverse the array from start to end.
For each element, check if it is already present in the set.
If it is not present, then add it to the set and print the element.

Python3




def distinct_elements(arr):
    distinct = set()
    for element in arr:
        if element not in distinct:
            print(element, end=' ')
            distinct.add(element)
 
arr = [12, 10, 9, 45, 2, 10, 10, 45]
distinct_elements(arr)
 
 
Output
12 10 9 45 2 

Time Complexity: O(n), where n is the length of the input array.
Auxiliary Space: O(n), where n is the length of the input array in the worst case when all elements are distinct.



Next Article
Count frequencies of all elements in array in Python using collections module

S

Shashank Mishra
Improve
Article Tags :
  • Python
  • Python dictionary-programs
  • python-dict
Practice Tags :
  • python
  • python-dict

Similar Reads

  • Program to print duplicates from a list of integers in Python
    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 SetSet 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
    3 min read
  • Count distinct elements in an array in Python
    Given an unsorted array, count all distinct elements in it. Examples: Input : arr[] = {10, 20, 20, 10, 30, 10} Output : 3 Input : arr[] = {10, 20, 20, 10, 20} Output : 2 We have existing solution for this article. We can solve this problem in Python3 using Counter method. Approach#1: Using Set() Thi
    2 min read
  • Count frequencies of all elements in array in Python using collections module
    Given an unsorted array of n integers which can contains n integers. Count frequency of all elements that are present in array. Examples: Input : arr[] = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 5] Output : 1 -> 4 2 -> 4 3 -> 2 4 -> 1 5 -> 2 This problem can be solved in many ways, refer
    2 min read
  • Different ways of sorting Dictionary by Keys and Reverse sorting by keys
    Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different w
    8 min read
  • Python | Minimum number of subsets with distinct elements using Counter
    You are given an array of n-element. You have to make subsets from the array such that no subset contain duplicate elements. Find out minimum number of subset possible. Examples: Input : arr[] = {1, 2, 3, 4} Output :1 Explanation : A single subset can contains all values and all values are distinct
    4 min read
  • Python | Count number of items in a dictionary value that is a list
    In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. A dictionary has multiple key:value pairs. There can be multiple pairs where value corresponding to a ke
    5 min read
  • Scraping And Finding Ordered Words In A Dictionary using Python
    What are ordered words? An ordered word is a word in which the letters appear in alphabetic order. For example abbey & dirt . The rest of the words are unordered for example geeks The task at hand This task is taken from Rosetta Code and it is not as mundane as it sounds from the above descripti
    3 min read
  • Python - Find all elements count in list
    In Python, counting the occurrences of all elements in a list is to determine how many times each unique element appears in the list. In this article, we will explore different methods to achieve this. The collections.Counter class is specifically designed for counting hashable objects. It provides
    3 min read
  • How to convert a dictionary into a NumPy array?
    It's sometimes required to convert a dictionary in Python into a NumPy array and Python provides an efficient method to perform this operation. Converting a dictionary to NumPy array results in an array holding the key-value pairs in the dictionary. Python provides numpy.array() method to convert a
    3 min read
  • 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
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