[Tutor] New to this list ....

Prasad, Ramit ramit.prasad at jpmorgan.com
Fri Mar 30 19:56:50 CEST 2012


[snip] 
>I'm used to c
> variables going out of scope once you leave the called function.  I
> imagine if you want to leave the variables unchanged, you have to
> re-assign them inside the function.
[snip]

Lists are mutable objects. When you pass a list to a function you bind 
a name in the functions namespace to the list object. Every name 
binding to that object will have the ability to modify the list. 

If you want to modify the list but not change it for others usually
you do something like

new_list = list( old_list )
OR  
new_list = old_list[:]

Now if you wanted to change an immutable object (like int) then you 
would have to return object because the name binding is only the 
function's scope. It should also be noted that you can modify
the list but you cannot reassign the list from the function.
Consider:

>>> 
>>> def blah( a ):
...     a = [] 
...     
>>> b = [ 1, 3, 4 ] 
>>> blah( b )
>>> print b
[1, 3, 4]
>>>

The reason b is untouched is because a = [] just binds the name 'a' to
a new list object while the name 'b' is still bound to the original 
list object. To bind 'b' to the new list I would have had to return it
from blah().

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list