[Tutor] Advice Please

dn PyTutor at danceswithmice.info
Tue Jun 16 19:32:04 EDT 2020


On 17/06/20 3:17 AM, Alan Gauld via Tutor wrote:
> 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.


Recommend playing with the Python Tutor (http://www.pythontutor.com/). 
If you try these (earlier) snippets, it enables one to step-through the 
code whilst showing stack-frames and illustrating "scope".

Some Python-editors offer a similar 'visual programming' experience.

The term "variable" (which most of us 'bandy around' quite happily) has 
a substantively different meaning in Python (than it does in other 
languages), eg a name in Python will point to a value, but a name may 
not point to another name, ie:

 >>> a = 1
 >>> b = a
 >>> a
1
 >>> b
1
 >>> a = 2
 >>> a
2
 >>> b
1

Similarly, when 'passing' data to a function, the parameters are 
separate names from the arguments. However, there is the major 
difference in behavior between mutable and immutable, which is 
frequently a major 'gotcha' for newcomers (per above). The illustration 
PythonTutor provides is a positive means of reinforcing this learning!

Thus, many 'traditional' discussions of "pass by reference"/"pass by 
value" no longer apply, because neither quite applies. They don't have a 
place within the Python model.
-- 
Regards =dn


More information about the Tutor mailing list