Python3 Func Id
# Python id() Function
The `id()` function is a built-in Python function used to retrieve the unique identifier of an object.
In Python, every entity (variables, lists, functions, classes, etc.) is treated as an object. Each object is assigned a unique integer identifier that remains constant throughout its entire lifetime. The `id()` function returns this identifier, which in CPython (the standard Python implementation) corresponds directly to the object's memory address.
> **Etymology**: The name `id` is short for **identifier**.
---
## Syntax and Parameters
### Syntax
```python
id(object)
```
### Parameters
* **`object`**: Any valid Python object (such as integers, strings, lists, custom class instances, functions, etc.).
### Return Value
* Returns an **integer** representing the unique identity of the object.
* **Guaranteed Uniqueness**: No two co-existing objects can share the same `id()`. However, once an object is garbage-collected, its memory address (and thus its `id`) may be reused by a newly created object.
---
## Code Examples
### Example 1: Basic Usage
This example demonstrates how to retrieve the unique identifier for different types of built-in objects.
```python
# Get the id of an integer
a = 10
print(id(a)) # Output: A unique integer, e.g., 140716345612352
# Get the id of a string
s = "hello"
print(id(s)) # Output: A unique integer, e.g., 140716345894128
# Get the id of a list
lst = [1, 2, 3]
print(id(lst)) # Output: A unique integer, e.g., 2341203485120
```
**Key Takeaways:**
1. Every object in memory has a unique ID.
2. Different objects generally have different IDs.
---
### Example 2: Verifying Object Identity
You can use `id()` to check whether two variables point to the exact same object in memory.
```python
# Multiple references to the same object
a = [1, 2, 3]
b = a
print(id(a) == id(b)) # Output: True (a and b point to the exact same object)
# Copying an object (creates a new object with identical content)
a = [1, 2, 3]
b = a.copy()
print(id(a) == id(b)) # Output: False (a and b are different objects in memory)
# Integer Caching (Small Integer Optimization)
a = 256
b = 256
print(id(a) == id(b)) # Output: True (Small integers between -5 and 256 are cached by Python)
a = 257
b = 257
print(id(a) == id(b)) # Output: False (Larger integers are generally not cached)
```
**Expected Output:**
```text
True
False
True
False
```
**Key Takeaways:**
* Comparing `id(a) == id(b)` is functionally equivalent to using Python's identity operator: `a is b`.
* Python optimizes memory usage by caching small integers (typically from `-5` to `256`) and short strings (interning). Therefore, multiple variables assigned these values will point to the same memory address.
---
### Example 3: Practical Applications
The `id()` function is highly useful for debugging, checking object identity, and understanding Python's memory management.
```python
# 1. Function to check if two variables reference the same object
def check_same_object(a, b):
return id(a) == id(b)
list1 = [1, 2, 3]
list2 = list1
list3 = [1, 2, 3]
print(check_same_object(list1, list2)) # Output: True
print(check_same_object(list1, list3)) # Output: False
# 2. Using objects as dictionary keys
# Python dictionaries use hash values and object identity to look up keys.
d = {}
obj = object()
d = "value"
print(d) # Output: value
# 3. Debugging class instances and class objects
class Person:
pass
p = Person()
print(f"Instance ID: {id(p)}") # Unique ID of the instance
print(f"Class ID: {id(Person)}") # Unique ID of the Class object itself
```
**Expected Output:**
```text
True
False
value
Instance ID: 1402348923408
Class ID: 1402348572832
```
---
## Important Considerations
1. **The `is` Operator vs. `id()`**:
While `id(a) == id(b)` is a valid way to check if two variables refer to the same object, the idiomatic and more readable Python way is to use the `is` operator:
```python
# Recommended
if a is b:
pass
# Equivalent but less Pythonic
if id(a) == id(b):
pass
```
2. **Object Lifetime and ID Reuse**:
An object's ID is only guaranteed to be unique and constant **during its lifetime**. Once an object is deleted or garbage-collected, Python may reuse its memory address for a new object.
```python
# Example of ID reuse
id1 = id( [1, 2, 3] ) # The list is created and immediately garbage-collected
id2 = id( [4, 5, 6] ) # A new list is created, potentially at the same memory address
print(id1 == id2) # Might output True, even though they are different lists
```
3. **Implementation Dependency**:
In CPython, `id()` returns the actual memory address of the object. However, other Python implementations (such as Jython, IronPython, or PyPy) might return a different unique sequence number or identifier. You should not write code that relies on the returned integer being a physical memory address.
YouTip