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 all distinct elements of a given integer array in Python | Ordered Dictionary
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
Program to print all distinct elements of a given integer array in Python | Ordered Dictionary

S

Shashank Mishra
Improve
Article Tags :
  • Python
  • python-dict
  • Python dictionary-programs
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
    2 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
    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
    Output of python program | Set 14 (Dictionary)
    Prerequisite: Dictionary Note: Output of all these programs is tested on Python31) What is the output of the following program? PYTHON3 D = dict() for x in enumerate(range(2)): D[x[0]] = x[1] D[x[1]+7] = x[0] print(D) a) KeyError b) {0: 1, 7: 0, 1: 1, 8: 0} c) {0: 0, 7: 0, 1: 1, 8: 1} d) {1: 1, 7: 2
    3 min read
    Group List of Dictionary Data by Particular Key in Python
    Our task is to group the data based on a particular key across these dictionaries. This involves collecting all values associated with a specific key into a single group. For example, if we have a list of dictionaries like this: [{'id': 1, 'name': 'Alice', 'age': 25}, {'id': 2, 'name': 'Bob', 'age':
    3 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