[Tutor] Advice Please

Alan Gauld alan.gauld at yahoo.co.uk
Tue Jun 16 11:17:42 EDT 2020


On 16/06/2020 09:04, John Weller wrote:
> Many thanks to all who replied - problem solved!!

Just one other point that i don;t think anyone else
picked up specifically.

>> pass the parameters to the function by reference so as to be able to 
>> access the values outside the function however I understand that this 
>> is not available in Python.  

Python is closer to pass by reference than it is to pass by value.
In python variables(and that includes function parameters) are
merely names that refer to objects. So a function parameter is
a name to which an object can be attached.

If that object is mutable (list, dict, class etc) you can change
it inside the function and the change will be apparent outside the
function too. If its immutable a new value will be created and
assigned to the parameter name but the original variable will
still refer to the original object.

Once you get used to that idea it all makes sense but for beginners
to the language it is quite different to how most languages work.

Here is an example:

def changeSeq(seq):
    seq[0] = 42   # mutable list
    return seq

lst = [1,2,3]
changeSeq(lst)
print(lst)  -> [42,2,3]


def changeVal(val):
    val = 42   # immutable integer
    return val

x = 66
changeVal(x)
print(x)  -> 66

Of course the cleanest way is always to reassign the
function return value. In both cases above:

lst = changeSeq(lst)   -> [42,2,3]
x = changeVal(x)       -> 42

This is not an expensive option since the objects are
not being copied, it is just a reassignment of the
reference in both cases.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list