[Python] Pointers/references in Python, part II

Previously. Pointers employed in Python, they are just hidden.

#!/usr/bin/env python3

def f(x):
    x.append(123)

foo=[]
f(foo)
f(foo)
print (foo)
[123, 123]

What you see here is called call by reference (rather than by value). A pointer is passed rather than a whole list. You can use dictionary or set instead. It's like to pass a pointer to an object in pure C or C++.

This is useful when you have a function that add some data to a global list.

Compare:

#!/usr/bin/env python3

def f():
    lst=[]
    lst.append(123)
    lst.append(456)
    return lst

foo=[]
foo=foo+f()
foo=foo+f()
print (foo)

With:

#!/usr/bin/env python3

def f(out):
    out.append(123)
    out.append(456)

foo=[]
f(foo)
f(foo)
print (foo)

In the second example, f() adds data directly to a list, pointer to which was passed. No need for additional list copying.

This can create a problem, however: f() can garble the list in a way that will be slightly harder to debug.

(the post first published at 20230410.)


List of my other blog posts.

Subscribe to my news feed

Yes, I know about these lousy Disqus ads. Please use adblocker. I would consider to subscribe to 'pro' version of Disqus if the signal/noise ratio in comments would be good enough.