Pointers in Python

Python doesn’t have pointers in the same way as languages like C or Go. Instead, Python uses object references. However, we can demonstrate similar concepts using mutable and immutable types.

def zero_value(val):
    val = 0

def zero_reference(lst):
    lst[0] = 0

def main():
    # Using an integer (immutable)
    i = 1
    print("initial:", i)

    zero_value(i)
    print("zero_value:", i)

    # Using a list (mutable)
    l = [1]
    zero_reference(l)
    print("zero_reference:", l[0])

    # Printing the object's id (similar to a memory address)
    print("object id:", id(i))

if __name__ == "__main__":
    main()

In this Python example, we demonstrate the difference between passing by value and passing by reference:

  1. The zero_value function takes an integer parameter. Integers are immutable in Python, so this function doesn’t affect the original value.

  2. The zero_reference function takes a list parameter. Lists are mutable in Python, so changes made inside the function affect the original list.

  3. In the main function, we first use an integer to show that zero_value doesn’t change the original value.

  4. Then we use a list to show that zero_reference does change the original value.

  5. Finally, we print the id of the integer, which is somewhat analogous to printing a memory address in languages with explicit pointers.

When you run this program, you’ll see output like this:

initial: 1
zero_value: 1
zero_reference: 0
object id: 140721639136144

Note that zero_value doesn’t change the original integer, but zero_reference does change the list. This is because integers are immutable in Python (similar to pass-by-value), while lists are mutable (similar to pass-by-reference).

The id function returns a unique identifier for an object, which remains constant for the life of the object. This is the closest equivalent in Python to a memory address in languages with explicit pointers.

Remember, Python handles memory management automatically, so you don’t need to worry about explicit memory addresses or pointer arithmetic as you would in languages like C or Go.