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:
zip() in Python
Next article icon

type() function in Python

Last Updated : 09 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three arguments. If a single argument type(obj) is passed, it returns the type of the given object. If three argument types (object, bases, dict) are passed, it returns a new type object. 

Python type() function Syntax

Syntax: type(object, bases, dict)

Parameters : 

  • object: Required. If only one parameter is specified, the type() function returns the type of this object
  • bases : tuple of classes from which the current class derives. Later corresponds to the __bases__ attribute. 
  • dict : a dictionary that holds the namespaces for the class. Later corresponds to the __dict__ attribute.

Return: returns a new type class or essentially a metaclass.

How type() Function Works in Python?

In the given example, we are printing the type of variable x. We will determine the type of an object in Python.

Python
x = 10 print(type(x)) 

Output
<class 'int'>

Examples of the type() function in Python

By using type() function, we can determine the type of an object in Python. Below are some more examples related to type() function:

Finding the type of a Python object

Here we are checking the object type using the type() function in Python.

Python
a = ("Geeks", "for", "Geeks") b = ["Geeks", "for", "Geeks"] c = {"Geeks": 1, "for":2, "Geeks":3} d = "Hello World" e = 10.23 f = 11.22  print(type(a)) print(type(b)) print(type(c)) print(type(d)) print(type(e)) print(type(f)) 

Output
<class 'tuple'> <class 'list'> <class 'dict'> <class 'str'> <class 'float'> <class 'float'>

Check if an Object is of Type in Python

In this example, we are testing the object using conditions, and printing the boolean.

Python
print(type([]) is list)  print(type([]) is not list)  print(type(()) is tuple)  print(type({}) is dict)  print(type({}) is not list) 

Output
True False True True True

Using type() with Conditional Statement

In this example , we are using type() function to determine the type of an object in Python with conditional if-else statement.

Python
# Example variables my_tuple = (10, 'Hello', 45, 'Hi') my_dict = {1: 'One', 2: 'Two', 3: 'Three'}  # Check if the variables have the same object type if type(my_tuple) is not type(my_dict):     print("The variables have different object types.") else:     print("The variables have the same object type.") 

Output
The variables have different object types.

Python type() With 3 Parameters

In the given example, we are creating a class without a base class and a class derived from a base class. The type() function allows for programmatically defining classes and their attributes at runtime.

Python
# New class(has no base) class with the # dynamic class initialization of type() new = type('New', (object, ),            dict(var1='GeeksforGeeks', b=2009))  # Print type() which returns class 'type' print(type(new)) print(vars(new))   # Base class, incorporated # in our new class class test:     a = "Geeksforgeeks"     b = 2009   # Dynamically initialize Newer class # It will derive from the base class test newer = type('Newer', (test, ),              dict(a='Geeks', b=2018))  print(type(newer)) print(vars(newer)) 

Output

<class ‘type’>

{‘var1’: ‘GeeksforGeeks’, ‘b’: 2009, ‘__module__’: ‘__main__’, ‘__dict__’: <attribute ‘__dict__’ of ‘New’ objects>, ‘__weakref__’: <attribute ‘__weakref__’ of ‘New’ objects>, ‘__doc__’: None}

<class ‘type’>

{‘a’: ‘Geeks’, ‘b’: 2018, ‘__module__’: ‘__main__’, ‘__doc__’: None}

Applications of Python type() Function 

  • type() function is basically used for debugging purposes. When using other string functions like .upper(), .lower(), and .split() with text extracted from a web crawler, it might not work because they might be of different type which doesn’t support string functions. And as a result, it will keep throwing errors, which are very difficult to debug [Consider the error as GeneratorType has no attribute lower() ]. 
  • type() function can be used at that point to determine the type of text extracted and then change it to other forms of string before we use string functions or any other operations on it.
  • type() with three arguments can be used to dynamically initialize classes or existing classes with attributes. It is also used to register database tables with SQL.
  • In unit testing frameworks, type() can be used to validate the output of functions or methods, ensuring that the expected data types are returned.


Next Article
zip() in Python
author
retr0
Improve
Article Tags :
  • Programming Language
  • Python
  • python
  • Python-Built-in-functions
Practice Tags :
  • python
  • python

Similar Reads

  • Python min() Function
    Python min() function returns the smallest value from a set of values or the smallest item in an iterable passed as its parameter. It's useful when you need to quickly determine the minimum value from a group of numbers or objects. For example: [GFGTABS] Python a = [23,25,65,21,98] print(min(a)) b =
    4 min read
  • Python next() method
    Python's next() function returns the next item of an iterator. Example Let us see a few examples to see how the next() method in Python works. C/C++ Code l_iter = iter(l) print(next(l_iter)) Output1 Note: The .next() method was a method for iterating over a sequence in Python 2. It has been replaced
    4 min read
  • Python oct() Function
    Python oct() function takes an integer and returns the octal representation in a string format. In this article, we will see how we can convert an integer to an octal in Python. Python oct() Function SyntaxSyntax : oct(x) Parameters: x - Must be an integer number and can be in either binary, decimal
    2 min read
  • ord() function in Python
    Python ord() function returns the Unicode code of a given single character. It is a modern encoding standard that aims to represent every character in every language. Unicode includes: ASCII characters (first 128 code points)Emojis, currency symbols, accented characters, etc.For example, unicode of
    2 min read
  • pow() Function - Python
    pow() function in Python is a built-in tool that calculates one number raised to the power of another. It also has an optional third part that gives the remainder when dividing the result. Example: [GFGTABS] Python print(pow(3,2)) [/GFGTABS]Output9 Explanation: pow(3, 2) calculates 32 = 9, where the
    2 min read
  • Python print() function
    The python print() function as the name suggests is used to print a python object(s) in Python as standard output. Syntax: print(object(s), sep, end, file, flush) Parameters: Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into s
    2 min read
  • Python range() function
    The Python range() function returns a sequence of numbers, in a given range. The most common use of it is to iterate sequences on a sequence of numbers using Python loops. Example In the given example, we are printing the number from 0 to 4. [GFGTABS] Python for i in range(5): print(i, end="
    7 min read
  • Python reversed() Method
    reversed() function in Python lets us go through a sequence like a list, tuple or string in reverse order without making a new copy. Instead of storing the reversed sequence, it gives us an iterator that yields elements one by one, saving memory. Example: [GFGTABS] Python a = ["nano",
    4 min read
  • round() function in Python
    Python round() function is a built-in function available with Python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer. In this
    6 min read
  • Python slice() function
    In this article, we will learn about the Python slice() function with the help of multiple examples. Example C/C++ Code String = 'Hello World' slice_obj = slice(5,11) print(String[slice_obj]) Output: World A sequence of objects of any type (string, bytes, tuple, list, or range) or the object which i
    5 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