Using the type() and id() Functions in Python
Course: Python Training Course
Topic: Using the type() and id() Functions
Course Link: Python Training Course at JustAcademy
Demo Registration: Register for a Course Demo
Website: Visit JustAcademy
1. Introduction to type() and id() Functions
Python provides several built-in functions that help programmers inspect objects and understand how they behave. Two important functions are type() and id().
The type() function identifies the type or class of an object. It helps determine whether a value is an integer, string, list, dictionary, tuple, or another Python object.
The id() function returns an integer representing the identity of an object. This identity remains constant during that object's lifetime. Two objects that exist at different times may have the same identity value, so an ID should not be treated as a permanent or globally unique identifier.
These functions are particularly useful when learning Python data types, investigating object behavior, debugging programs, and understanding the difference between variables and objects.
Example: Using Both Functions
name = "Python"
age = 25
prices = [100, 200, 300]
print(type(name))
print(type(age))
print(type(prices))
print(id(name))
print(id(age))
print(id(prices))
Explanation:
type(name) identifies the string type.
type(age) identifies the integer type.
type(prices) identifies the list type.
id() returns an identity value for each object.
The numeric values returned by id() can differ between program executions and Python implementations.
2. Learning Objectives
After studying this topic, learners should be able to:
- Understand the purpose of Python's
type() function.
- Identify built-in and user-defined object types.
- Understand the purpose and behavior of
id().
- Distinguish object identity from object equality.
- Understand how variables refer to objects.
- Investigate mutable and immutable objects.
- Use
type(), id(), is, ==, and isinstance() appropriately.
- Apply these functions to practical debugging and programming scenarios.
3. Understanding the type() Function
The built-in type() function returns the type of an object. In its most common form, it accepts one argument.
Syntax:
type(object)
Here, object is the value or object whose type you want to inspect.
3.1 Basic Example
number = 100
decimal_number = 25.75
message = "Hello Python"
is_active = True
print(type(number))
print(type(decimal_number))
print(type(message))
print(type(is_active))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
Explanation:
int represents integer values.
float represents floating-point values.
str represents text strings.
bool represents Boolean values, such as True and False.
3.2 Checking Numeric Data Types
The type() function can identify different numeric types in Python.
integer_value = 50
float_value = 50.5
complex_value = 3 + 4j
print(type(integer_value))
print(type(float_value))
print(type(complex_value))
Output:
<class 'int'>
<class 'float'>
<class 'complex'>
This is useful when working with calculations and checking whether a variable contains the expected numeric type.
3.3 Checking Collection Types
Python includes several collection types, such as lists, tuples, sets, and dictionaries. You can use type() to identify each one.
student_list = ["Aarav", "Riya", "Kabir"]
student_tuple = ("Aarav", "Riya", "Kabir")
student_set = {"Aarav", "Riya", "Kabir"}
student_dict = {"name": "Aarav", "age": 21}
print(type(student_list))
print(type(student_tuple))
print(type(student_set))
print(type(student_dict))
Output:
<class 'list'>
<class 'tuple'>
<class 'set'>
<class 'dict'>
4. Common Python Types and Their Identification
| Data Type |
Example Value |
Expression |
Returned Type |
| Integer |
25 |
type(25) |
int |
| Float |
25.5 |
type(25.5) |
float |
| Complex |
2 + 3j |
type(2 + 3j) |
complex |
| String |
"Python" |
type("Python") |
str |
| Boolean |
True |
type(True) |
bool |
| List |
[1, 2, 3] |
type([1, 2, 3]) |
list |
| Tuple |
(1, 2, 3) |
type((1, 2, 3)) |
tuple |
| Set |
{1, 2, 3} |
type({1, 2, 3}) |
set |
| Dictionary |
{"a": 1} |
type({"a": 1}) |
dict |
| None |
None |
type(None) |
NoneType |
5. Understanding the id() Function
The built-in id() function returns an integer that identifies an object during its lifetime.
Syntax:
id(object)
The argument can be a variable, literal, collection, function, class instance, or another Python object.
5.1 Basic Example
name = "Python"
age = 25
numbers = [10, 20, 30]
print(id(name))
print(id(age))
print(id(numbers))
Explanation:
- Each call returns an integer representing the identity of the referenced object.
- The ID remains constant while that particular object exists.
- The returned numbers are implementation-dependent and should not be hard-coded into programs.
- Python does not promise that IDs are different for objects whose lifetimes do not overlap.
5.2 Checking an Object's Identity
If two variables refer to the same object, calling id() on either variable returns the same identity value while that object remains alive.
first = [1, 2, 3]
second = first
print(id(first))
print(id(second))
print(id(first) == id(second))
Output:
# The first two lines show the same ID.
True
The exact numeric ID is not predictable, but the comparison is true because both variables refer to the same list object.
6. Understanding Variables and Objects
In Python, a variable is a name that refers to an object. Assigning one variable to another does not necessarily create a new object. It may simply create another reference to the existing object.
6.1 Two Variables Referring to One Object
first_name = "Aarav"
second_name = first_name
print(first_name)
print(second_name)
print(id(first_name))
print(id(second_name))
print(first_name is second_name)
Both variables refer to the same string object in this assignment. Therefore, their identities match while that object remains alive.
6.2 Reassigning a Variable
When a variable is reassigned, it may begin referring to a different object. The previous object can remain alive if another reference still points to it.
value = [10, 20]
another_value = value
print(value is another_value)
value = [30, 40]
print(value)
print(another_value)
print(value is another_value)
Output:
True
[30, 40]
[10, 20]
False
Explanation: Initially, both variables refer to the same list. After value is reassigned to a new list, another_value continues to refer to the original list.
7. Difference Between type() and id()
Although both functions inspect objects, they answer different questions.
| Feature |
type() |
id() |
| Purpose |
Identifies an object's type. |
Returns an object's identity integer. |
| Input |
A Python object. |
A Python object. |
| Return value |
A type or class object. |
An integer. |
| Example |
type("Hello") |
id("Hello") |
| Typical use |
Type inspection and debugging. |
Inspecting identity and references. |
| Does it change after reassignment? |
The type depends on the object currently referenced. |
The ID depends on the object currently referenced. |
Example Comparing Both Functions
value = 100
print("Type:", type(value))
print("Identity:", id(value))
value = "Python"
print("New type:", type(value))
print("New identity:", id(value))
The variable name value first refers to an integer object and later refers to a string object. The type and identity displayed after reassignment describe the new object.
8. Difference Between == and is
Understanding type() and id() becomes easier when you also understand the difference between equality and identity.
== checks whether two objects are equal according to their equality rules.
is checks whether two references point to the exact same object.
8.1 Equal Values but Different Objects
list_a = [1, 2, 3]
list_b = [1, 2, 3]
print(list_a == list_b)
print(list_a is list_b)
Output:
True
False
The lists contain equal values, but they are two separate list objects. Therefore, equality is true while identity is false.
8.2 Two References to the Same Object
list_a = [1, 2, 3]
list_b = list_a
print(list_a == list_b)
print(list_a is list_b)
Output:
True
True
Here, list_b = list_a creates another reference to the same list object.
8.3 When Should You Use is?
Use is when checking object identity, particularly when checking for singleton values such as None.
result = None
if result is None:
print("No result is available")
For ordinary value comparisons, use ==. Avoid using is to compare strings or numbers merely because their values appear equal.
9. Object Identity and Mutable Objects
Mutable objects can be changed after creation. Lists, dictionaries, and sets are common examples. When a mutable object is modified in place, its identity normally remains the same.
9.1 Modifying a List
numbers = [10, 20, 30]
original_id = id(numbers)
numbers.append(40)
updated_id = id(numbers)
print(numbers)
print(original_id == updated_id)
Output:
[10, 20, 30, 40]
True
The list contents change, but the same list object is modified in place.
9.2 Creating a New List
numbers = [10, 20, 30]
original_id = id(numbers)
numbers = numbers + [40]
print(numbers)
print(original_id == id(numbers))
The expression numbers + [40] creates a new list and assigns it to numbers. The previous list may be released if no references to it remain.
Do not depend on the new list's numerical ID being different in every possible program scenario if the original object has already been destroyed. Python's identity guarantee applies during an object's lifetime.
10. Object Identity and Immutable Objects
Immutable objects cannot be changed in place. Common examples include integers, floats, strings, and tuples. An operation that appears to modify an immutable value instead produces or selects a value and binds the variable to an object representing that result.
10.1 Reassigning an Integer
number = 10
old_id = id(number)
number = number + 5
print(number)
print(old_id == id(number))
The expression number + 5 calculates a new integer value, and the variable is rebound to that value. Do not assume that the identity must always change or remain the same, because implementations may reuse objects for certain values.
10.2 Strings Are Immutable
message = "Hello"
alias = message
print(message is alias)
message = message + " Python"
print(message)
print(alias)
Output:
True
Hello Python
Hello
String concatenation produces a new string value. The variable alias continues to refer to the original string.
11. Understanding Python Object Identity and Memory
Python manages objects and their lifetimes automatically. The id() function exposes an identity value, but its implementation details depend on the Python implementation.
In CPython, the ID is typically the memory address associated with the object. This is an implementation detail, not a portable guarantee for all Python implementations.
For general Python programming:
- Use
id() to inspect object identity during debugging and learning.
- Do not treat an ID as a permanent database key or unique identifier across program runs.
- Do not assume that equal values always have the same identity.
- Do not assume that unequal values always have different IDs at different points in time.
- Use equality checks for values and identity checks when object identity is what matters.
Example: A Safe Identity Check
data = [1, 2, 3]
reference = data
if data is reference:
print("Both variables reference the same object")
if data == reference:
print("Both objects have equal values")
12. Using isinstance() Alongside type()
The type() function is useful when you need to inspect an object's exact type. The isinstance() function is often more appropriate when checking whether an object belongs to a particular type or subclass.
12.1 Using type()
age = 21
if type(age) is int:
print("The exact type is int")
12.2 Using isinstance()
age = 21
if isinstance(age, int):
print("The value is an instance of int")
For many ordinary type checks, isinstance() is preferred because it supports inheritance and compatible types.
12.3 A Special Case: bool and int
In Python, bool is a subclass of int. This means a Boolean value passes an isinstance() check for integers.
print(isinstance(True, int))
print(type(True) is int)
print(type(True) is bool)
Output:
True
False
True
If an application must accept only actual integers and reject Boolean values, a check such as type(value) is int can be appropriate.
13. Using type() with User-Defined Classes
Python allows programmers to define custom classes. Instances created from those classes have their own type information.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
student1 = Student("Aarav", 85)
print(type(student1))
print(type(student1.name))
print(type(student1.marks))
Output:
<class '__main__.Student'>
<class 'str'>
<class 'int'>
The first output identifies the user-defined Student class. The other outputs identify the types of the object's attributes.
13.1 Inspecting Object Identity
class Student:
def __init__(self, name):
self.name = name
student1 = Student("Riya")
student2 = Student("Riya")
student3 = student1
print(student1 == student2)
print(student1 is student2)
print(student1 is student3)
print(id(student1))
print(id(student2))
print(id(student3))
Unless the class defines custom equality behavior, two separately created instances compare unequal by default. student1 and student2 are separate objects, while student3 refers to the same object as student1.
14. Using type() and id() for Debugging
Debugging involves finding and correcting problems in a program. The type() and id() functions can help investigate unexpected values and references.
14.1 Debugging Unexpected Data Types
price = input("Enter price: ")
print("Value:", price)
print("Type:", type(price))
The value returned by input() is a string, even if the user enters digits. If you want to perform numeric calculations, convert the input to a suitable numeric type.
price = float(input("Enter price: "))
print("Value:", price)
print("Type:", type(price))
14.2 Debugging Shared References
original = [1, 2, 3]
copy_reference = original
print(id(original))
print(id(copy_reference))
copy_reference.append(4)
print(original)
print(copy_reference)
Both variables display the updated list because they refer to the same mutable object. Inspecting identity helps reveal this relationship.
14.3 Debugging Unexpected Reassignment
value = 100
print("Before:", value, type(value), id(value))
value = "One hundred"
print("After:", value, type(value), id(value))
This example shows how reassignment changes the value and type associated with a variable name. The ID describes the object currently referenced.
15. Common Mistakes When Using type() and id()
| Mistake |
Example |
Explanation and Solution |
| Confusing type with a string |
type(10) == "int" |
type(10) returns a class object, not the string "int". Use type(10) is int or isinstance(10, int). |
| Assuming equal values are the same object |
[1, 2] is [1, 2] |
Two separately created lists can contain equal values but have different identities. |
| Using is for ordinary equality |
name1 is name2 |
Use == to compare values unless object identity is specifically required. |
| Assuming an ID is permanent |
Saving an ID for later use |
Object IDs are guaranteed only during the object's lifetime. Use an application-level identifier when a persistent ID is required. |
| Assuming IDs are memory addresses everywhere |
Interpreting id() as an address |
This is typical of CPython, but not a language-wide guarantee. |
| Assuming mutable objects change identity when modified |
items.append(4) |
In-place mutation normally keeps the same object identity. |
| Forgetting input returns a string |
type(input("Age: ")) |
The result is str. Convert it before numeric calculations. |
| Confusing type() and isinstance() |
Using exact-type checks everywhere |
Use isinstance() when subclass compatibility is desired. |
16. Practical Example: Inspecting Student Records
Objective: Create a program that inspects the types and identities of different objects used in a student record.
student = {
"name": "Aarav",
"age": 21,
"marks": [85, 90, 88],
"active": True
}
print("Student record type:", type(student))
print("Student record ID:", id(student))
for key, value in student.items():
print("\nField:", key)
print("Value:", value)
print("Type:", type(value))
print("ID:", id(value))
How It Works
- A dictionary stores student information using keys and values.
type(student) identifies the dictionary type.
id(student) returns the identity of the dictionary object.
- The loop visits each key-value pair.
type(value) identifies whether each field contains a string, integer, list, or Boolean.
id(value) returns the identity of each value object.
The identity numbers are illustrative runtime values and should not be expected to match across different executions.
17. Practical Example: Understanding List References
Objective: Demonstrate the difference between creating an alias and making a shallow copy of a list.
original = [10, 20, 30]
alias = original
shallow_copy = original.copy()
print("Original ID:", id(original))
print("Alias ID:", id(alias))
print("Copy ID:", id(shallow_copy))
print("Original is alias:", original is alias)
print("Original is copy:", original is shallow_copy)
alias.append(40)
print("Original:", original)
print("Alias:", alias)
print("Shallow copy:", shallow_copy)
Expected behavior:
original and alias refer to the same list.
shallow_copy is a separate list object with the same initial elements.
- Appending to
alias changes the list visible through original.
- The separate shallow copy remains unchanged because its outer list is a different object.
A shallow copy duplicates the outer collection but does not recursively copy nested objects. If the list contains other mutable collections, those nested objects may still be shared.
18. Practical Example: Checking and Validating Input Types
Objective: Accept a value, convert it to a numeric type, and inspect the result.
user_input = input("Enter a number: ")
try:
number = float(user_input)
print("Converted value:", number)
print("Data type:", type(number))
print("Object identity:", id(number))
except ValueError:
print("Invalid input. Please enter a valid numeric value.")
This example shows how type inspection can be combined with exception handling. The program converts valid numeric input to a float and displays its type and identity. Invalid text is handled with a ValueError exception.
19. Hands-On Exercises
Exercise 1: Identify Data Types
Create variables containing an integer, float, string, Boolean, list, tuple, and dictionary. Use type() to display each object's type.
Exercise 2: Compare Object Identities
Create a list and assign it to two variables. Display both IDs and check whether the variables refer to the same object using is.
Exercise 3: Equality Versus Identity
Create two separate lists with identical contents. Compare them using == and is. Explain why the results differ.
Exercise 4: Reassignment
Create a variable containing an integer, display its type and ID, then reassign it to a string and display the new type and ID.
Exercise 5: Mutable Objects
Create a dictionary, record its ID, update one of its values, and check whether the dictionary's identity changed.
Exercise 6: Aliasing and Copying
Create a list, an alias, and a shallow copy. Compare their identities and observe how changes affect each variable.
Exercise 7: User-Defined Classes
Create a Product class with a name and price. Instantiate two products with the same values and compare their types, IDs, equality, and identity.
20. Mini Project: Python Object Inspector
Project Objective: Build a simple program that accepts several predefined Python values and displays their types, identities, and basic identity relationships.
# Python Object Inspector
values = [
100,
45.75,
"Python",
True,
[10, 20, 30],
(1, 2, 3),
{"name": "Riya", "age": 22},
None
]
for index, value in enumerate(values, start=1):
print("\nObject", index)
print("Value:", value)
print("Type:", type(value))
print("Identity:", id(value))
first_list = [1, 2, 3]
alias_list = first_list
copy_list = first_list.copy()
print("\nIdentity comparison")
print("First list is alias:", first_list is alias_list)
print("First list is copy:", first_list is copy_list)
print("First list equals copy:", first_list == copy_list)
Project Requirements
- Inspect at least eight different Python objects.
- Display each object's value, type, and identity.
- Create an alias and a shallow copy of a list.
- Compare the lists using both
is and ==.
- Explain the difference between equality and identity in your own words.
21. Interview Questions and Answers
Q1. What is the purpose of the type() function?
Answer: The type() function returns the type or class of an object. It is commonly used to inspect data types during development and debugging.
Q2. What is the purpose of the id() function?
Answer: The id() function returns an integer representing an object's identity. The identity remains constant for the lifetime of that object.
Q3. What does type(10) return?
Answer: It returns the class object int, displayed as <class 'int'>.
Q4. What does id() return?
Answer: It returns an integer identity value for the specified object. The exact value depends on the Python implementation and runtime.
Q5. What is the difference between type() and id()?
Answer: type() identifies an object's type, while id() returns its identity integer.
Q6. What is the difference between == and is?
Answer: == compares values according to equality rules. is checks whether two references point to the same object.
Q7. Can two different objects have equal values?
Answer: Yes. For example, two separately created lists containing [1, 2, 3] can compare equal using == while being different objects under is.
Q8. Does modifying a list change its ID?
Answer: Modifying a list in place, such as by using append(), normally preserves its identity because it is the same list object.
Q9. Does assigning one variable to another create a copy?
Answer: No. An assignment such as second = first creates another reference to the same object. Use an appropriate copy operation when a separate collection is needed.
Q10. Is id() always a memory address?
Answer: No. In CPython, an ID is typically associated with an object's memory address. Other Python implementations may use different mechanisms.
Q11. Can an object ID be reused?
Answer: Yes. Python guarantees that an object's ID remains constant during its lifetime, but IDs may be reused for objects whose lifetimes do not overlap.
Q12. When should isinstance() be used instead of type()?
Answer: Use isinstance() when checking whether an object belongs to a type or its subclasses. Use type() when the exact type is important.
Q13. Why does isinstance(True, int) return True?
Answer: Because bool is a subclass of int in Python.
Q14. How can type() and id() help with debugging?
Answer: They can reveal unexpected data types, help identify shared references, and clarify whether two variables point to the same object.
22. Quick Revision Checklist
type() returns an object's type or class.
id() returns an integer representing object identity.
- An object's identity remains constant during its lifetime.
- IDs may be reused after an object's lifetime ends.
- Variables are names that refer to objects.
- Assigning one variable to another does not automatically create a copy.
== checks equality, while is checks identity.
- Mutable objects can change in place without changing identity.
- Immutable values cannot be changed in place.
isinstance() supports checks involving subclasses.
- Use
is None to check whether a value is None.
- Do not use object IDs as permanent application identifiers.
23. Conclusion
The type() and id() functions are valuable tools for understanding Python objects. The type() function identifies what kind of object a variable references, while id() helps investigate the identity of that object during its lifetime.
When combined with concepts such as variable references, mutable and immutable objects, equality, identity, and type checking, these functions make Python programs easier to understand and debug. Practicing them with lists, dictionaries, strings, numeric values, and custom classes will build a strong foundation for more advanced Python programming.
Continue your learning through the Python Training Course at JustAcademy. You can register for a course demo or visit the JustAcademy website for more information.