I am never redefining the or reassigning the list when using validate
but since it spits the modified list back out that somehow means that
the modified list is part of the environment and not the old one.
i thought what happend inside a function stays inside a function
meaning what comes out is independent of what comes in.
Meaning if I want the list I send as a parameter to the function I
have to do x = func(x) and not just func(x) and x is magically what
comes out of func().
Doesnt Python have closure or that isnt what this is about?
def validate(placed ):
student = round(random.ra ndom()*401)
if student in placed:
return validate(placed )
else:
placed.append(s tudent)
return student, placed
def val(placed):
student = round(random.ra ndom()*401)
if student in placed:
return validate(placed )
else:
placed.append(s tudent)
return student
>>g = lambda x:validate(x) l=[] for x in range(1,10):
g(l)
(141.0, [141.0])
(19.0, [141.0, 19.0])
(86.0, [141.0, 19.0, 86.0])
(120.0, [141.0, 19.0, 86.0, 120.0])
(76.0, [141.0, 19.0, 86.0, 120.0, 76.0])
(262.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0])
(234.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0])
(74.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0])
(325.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0, 325.0])
>>g = lambda x:val(x) l=[] for x in range(1,10):
g(l)
183.0
33.0
315.0
244.0
308.0
168.0
146.0
378.0
297.0
>>>
11 1373
Python doesn't use value semantics for variables but reference semantics:
a = [1]
b = a
In many languages, you'd now have 2 lists. In Python you still have one list,
and both a and b refer to it.
Now if you modify the data (the list), both variables will change
a.append(2) # in-place modification of the list
print b # will print [1,2]
If you don't want this, you should make a copy somewhere
a = a + [2]
or
b = a[:]
It takes a bit of getting used to, but it is very handy in practice.
Read the docs about 'immutable' and 'mutable' types.
(I expected this to be a FAQ, but I couldn't quickly find a matching entry)
Albert
In article
<02************ *************** *******@z72g200 0hsb.googlegrou ps.com>,
ssecorp <ci**********@g mail.comwrote:
I am never redefining the or reassigning the list when using validate
but since it spits the modified list back out that somehow means that
the modified list is part of the environment and not the old one.
i thought what happend inside a function stays inside a function
meaning what comes out is independent of what comes in.
Meaning if I want the list I send as a parameter to the function I
have to do x = func(x) and not just func(x) and x is magically what
comes out of func().
A function cannot modify the value of a global variable
(unless it specifies "global"). It doesn't reassign anything.
But in the functions below you're not reassigning a variable,
you're _modifiying_ an object. A function _can_ modify an
object you pass to it:
>>def DoesntReassign( x):
.... x = 0
....
>>def Modifies(x):
.... x.append(0)
....
>>x=42 DoesntReassig n(x) x
42
>>x=[] Modifies(x) x
[0]
Hmm, look at this:
>>x=[] id(x)
404296
>>Modifies(x) x
[0]
>>id(x)
404296
'x' refers to exactly the same object before and after
the call to Modifies. The function has _modified_ that
object, but it hasn't redefined or reassigned anything.
Doesnt Python have closure or that isnt what this is about?
def validate(placed ):
student = round(random.ra ndom()*401)
if student in placed:
return validate(placed )
else:
placed.append(s tudent)
return student, placed
def val(placed):
student = round(random.ra ndom()*401)
if student in placed:
return validate(placed )
else:
placed.append(s tudent)
return student
>g = lambda x:validate(x) l=[] for x in range(1,10):
g(l)
(141.0, [141.0])
(19.0, [141.0, 19.0])
(86.0, [141.0, 19.0, 86.0])
(120.0, [141.0, 19.0, 86.0, 120.0])
(76.0, [141.0, 19.0, 86.0, 120.0, 76.0])
(262.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0])
(234.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0])
(74.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0])
(325.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0, 325.0])
>g = lambda x:val(x) l=[] for x in range(1,10):
g(l)
183.0
33.0
315.0
244.0
308.0
168.0
146.0
378.0
297.0
>>
--
David C. Ullrich
David C. Ullrich wrote:
In article
<02************ *************** *******@z72g200 0hsb.googlegrou ps.com>,
ssecorp <ci**********@g mail.comwrote:
>I am never redefining the or reassigning the list when using validate but since it spits the modified list back out that somehow means that the modified list is part of the environment and not the old one. i thought what happend inside a function stays inside a function meaning what comes out is independent of what comes in. Meaning if I want the list I send as a parameter to the function I have to do x = func(x) and not just func(x) and x is magically what comes out of func().
A function cannot modify the value of a global variable
Yes it can.
>>a=[] def f():
a.append('yes I can')
>>f() a
['yes I can']
(unless it specifies "global"). It doesn't reassign anything.
The statement 'global a' would allow f to *rebind* the global *name*
'a'. The word 'variable' should almost not be used in discussing Python
since it is often unclear whether it refers to a name (or collection
slot) or an object bound thereto.
But in the functions below you're not reassigning a variable,
you're _modifiying_ an object. A function _can_ modify an
object you pass to it:
It can modify any mutable object it can access.
>Doesnt Python have closure or that isnt what this is about?
Python does have closures. This is not about that.
>def validate(placed ): student = round(random.ra ndom()*401) if student in placed: return validate(placed ) else: placed.append(s tudent) return student, placed
Delete this. It is redundant with the below.
>def val(placed): student = round(random.ra ndom()*401) if student in placed: return validate(placed ) else: placed.append(s tudent) return student
I believe this is equivalent to
def addval(placed):
while True:
student = round(random.ra ndom()*401)
if student not in placed:
break
placed.append(s tudent)
return student
While this avoids the indefinite recursion depth problem, it does not
avoid the indefinite time problem. Use random.shuffle, or write your
own version if doing this for practice. Also consider removing the
return statement unless you actually directly use the added value. It
is easier to remember that addval mutates 'placed' without the return.
>>>>g = lambda x:validate(x)
This is doubly diseased.
First, never write a 'name = lambda...' statement since it is equivalent
to a def statement except that the resulting function object lacks a
proper .funcname attribute. The above only trivially abbreviates
def g(x): return validate(x)
by 3 characters. Another reason is that the lambda form somehow more
often tricks people into the next mistake .
Second, never write a function (with either def or lambda) that simply
returns a function of the argument(s). The wrapping does nothing! This
is a waste of time and space for both you and the interpreter. The
above is functionally equivalent to
g = validate
and if you want that, you could name the function 'g' when you define it.
>>>>l=[]
In some fonts, 'l' and '1' are nearly identical; please use something
else for public code, which you made this to be by posting it;-)
>>>>for x in range(1,10):
g(l)
As said, the 'g' wrapper is useless.
addval(l)
Hope this helps.
Terry Jan Reedy
ty very good answer. i know i shouldn't use lambda like that, i never
do i was just playing around there and then this happened which i
thought was weird.
On Jul 10, 8:09*pm, Terry Reedy <tjre...@udel.e duwrote:
David C. Ullrich wrote:
In article
<02ff4326-7b07-4ae6-8607-f58ea6180...@z7 2g2000hsb.googl egroups.com>,
*ssecorp <circularf...@g mail.comwrote:
I am never redefining the or reassigning the list when using validate
but since it spits the modified list back out that somehow means that
the modified list is part of the environment and not the old one.
i thought what happend inside a function stays inside a function
meaning what comes out is independent of what comes in.
Meaning if I want the list I send as a parameter to the function I
have to do x = func(x) and not just func(x) and x is magically what
comes out of func().
A function cannot modify the value of a global variable
Yes it can.
*>>a=[]
*>>def f():
* * * * a.append('yes I can')
*>>f()
*>>a
['yes I can']
(unless it specifies "global"). It doesn't reassign anything.
The statement 'global a' would allow f to *rebind* the global *name*
'a'. *The word 'variable' should almost not be used in discussing Python
since it is often unclear whether it refers to a name (or collection
slot) or an object bound thereto.
But in the functions below you're not reassigning a variable,
you're _modifiying_ an object. A function _can_ modify an
object you pass to it:
It can modify any mutable object it can access.
Doesnt Python have closure or that isnt what this is about?
Python does have closures. *This is not about that.
def validate(placed ):
* * student = round(random.ra ndom()*401)
* * if student in placed:
* * * * return validate(placed )
* * else:
* * * * placed.append(s tudent)
* * * * return student, placed
Delete this. It is redundant with the below.
def val(placed):
* * student = round(random.ra ndom()*401)
* * if student in placed:
* * * * return validate(placed )
* * else:
* * * * placed.append(s tudent)
* * * * return student
I believe this is equivalent to
def addval(placed):
* *while True:
* * *student = round(random.ra ndom()*401)
* * *if student not in placed:
* * * *break
* *placed.append( student)
* *return student
While this avoids the indefinite recursion depth problem, it does not
avoid the indefinite time problem. *Use random.shuffle, or write your
own version if doing this for practice. *Also consider removing the
return statement unless you actually directly use the added value. *It
is easier to remember that addval mutates 'placed' without the return.
>>>g = lambda x:validate(x)
This is doubly diseased.
First, never write a 'name = lambda...' statement since it is equivalent
to a def statement except that the resulting function object lacks a
proper .funcname attribute. *The above only trivially abbreviates
* *def g(x): return validate(x)
by 3 characters. *Another reason is that the lambda form somehow more
often tricks people into the next mistake .
Second, never write a function (with either def or lambda) that simply
returns a function of the argument(s). *The wrapping does nothing! *This
is a waste of time and space for both you and the interpreter. *The
above is functionally equivalent to
* *g = validate
and if you want that, you could name the function 'g' when you define it.
>>>l=[]
In some fonts, 'l' and '1' are nearly identical; please use something
else for public code, which you made this to be by posting it;-)
>>>for x in range(1,10):
* * * *g(l)
As said, the 'g' wrapper is useless.
* * * * addval(l)
Hope this helps.
Terry Jan Reedy
>>def mod(x,y):
return x.append(y)
>>mod([1,2],3) k=[1,2,3] k
[1, 2, 3]
>>l = mod(k,4) l k
[1, 2, 3, 4]
>>l k==l
False
>>mod(k,5) k
[1, 2, 3, 4, 5]
>>mod(l,4)
Traceback (most recent call last):
File "<pyshell#2 9>", line 1, in <module>
mod(l,4)
File "<pyshell#1 8>", line 2, in mod
return x.append(y)
AttributeError: 'NoneType' object has no attribute 'append'
>>l l=k l
[1, 2, 3, 4, 5]
>>i=mod(k,1) i
same stuff but i dont find this intuitive.
On Jul 10, 9:46*pm, ssecorp <circularf...@g mail.comwrote:
>def mod(x,y):
* * * * return x.append(y)
append adds y to list x and returns None, which is then returned by
mod.
>
>mod([1,2],3) k=[1,2,3] k
[1, 2, 3]
>l = mod(k,4)
4 has been appended to list k and mod has returned None, so l is now
None.
>l k
[1, 2, 3, 4]
>l k==l
False
Because k is [1, 2, 3, 4] and l is None.
>mod(k,5) k
[1, 2, 3, 4, 5]
>mod(l,4)
Traceback (most recent call last):
* File "<pyshell#2 9>", line 1, in <module>
* * mod(l,4)
* File "<pyshell#1 8>", line 2, in mod
* * return x.append(y)
AttributeError: 'NoneType' object has no attribute 'append'
l is None, not a list, so it complains!
>l l=k l
[1, 2, 3, 4, 5]
>i=mod(k,1) i
same stuff but i dont find this intuitive.
It's usual for methods which modify to return None.
In article <ma************ *************** ***********@pyt hon.org>,
Terry Reedy <tj*****@udel.e duwrote:
David C. Ullrich wrote:
In article
<02************ *************** *******@z72g200 0hsb.googlegrou ps.com>,
ssecorp <ci**********@g mail.comwrote:
I am never redefining the or reassigning the list when using validate
but since it spits the modified list back out that somehow means that
the modified list is part of the environment and not the old one.
i thought what happend inside a function stays inside a function
meaning what comes out is independent of what comes in.
Meaning if I want the list I send as a parameter to the function I
have to do x = func(x) and not just func(x) and x is magically what
comes out of func().
A function cannot modify the value of a global variable
Yes it can.
>>a=[]
>>def f():
a.append('yes I can')
>>f()
>>a
['yes I can']
(unless it specifies "global"). It doesn't reassign anything.
The statement 'global a' would allow f to *rebind* the global *name*
'a'.
Aargh. That's exactly what I meant, sorry.
The word 'variable' should almost not be used in discussing Python
since it is often unclear whether it refers to a name (or collection
slot) or an object bound thereto.
Indeed. Which is exactly why I included those snippets of
code that you snipped, one of which does exactly what your
snippet above does... you're probably right, "variable" is
a bad idea, and "modify the value of a variable" is a very
bad idea.
The code doesn't "modify the value of the variable" in the
sense that the value of the variable is a certain object,
and after the function call the value is the same object.
It does "modify the value of the variable" in the sense
that the object which is the value of the variable has been
modified.
There's a problem here. Please note that this is not a criticism,
and I don't really know what anyone could do about the problem.
The problem is that if the reader is not accustomed to thinking
explicitly about what's going on under the hood when code is
executed he's going to have a hard time understanding the
difference between "assigning a value to a variable" and
"binding a name to an object". Once I realized that dicts
rule everything this became clear to me, but for some time
the discussions I saw on all this made no sense to me.
Which is why I think it's a good idea to include examples
illustrating what can and cannot be done, which is why I
did that. I tend to suspect that the OP is at least as
confused on the subtlties as I was back then (evidence below).
But in the functions below you're not reassigning a variable,
you're _modifiying_ an object. A function _can_ modify an
object you pass to it:
It can modify any mutable object it can access.
Doesnt Python have closure or that isnt what this is about?
Python does have closures. This is not about that.
This is why I suspect what I say I suspect. He's thought
that the word "closure" meant something like "local scope"...
def validate(placed ):
student = round(random.ra ndom()*401)
if student in placed:
return validate(placed )
else:
placed.append(s tudent)
return student, placed
Delete this. It is redundant with the below.
def val(placed):
student = round(random.ra ndom()*401)
if student in placed:
return validate(placed )
else:
placed.append(s tudent)
return student
I believe this is equivalent to
def addval(placed):
while True:
student = round(random.ra ndom()*401)
if student not in placed:
break
placed.append(s tudent)
return student
While this avoids the indefinite recursion depth problem, it does not
avoid the indefinite time problem. Use random.shuffle, or write your
own version if doing this for practice. Also consider removing the
return statement unless you actually directly use the added value. It
is easier to remember that addval mutates 'placed' without the return.
>>>g = lambda x:validate(x)
This is doubly diseased.
First, never write a 'name = lambda...' statement since it is equivalent
to a def statement except that the resulting function object lacks a
proper .funcname attribute. The above only trivially abbreviates
def g(x): return validate(x)
by 3 characters. Another reason is that the lambda form somehow more
often tricks people into the next mistake .
Second, never write a function (with either def or lambda) that simply
returns a function of the argument(s). The wrapping does nothing! This
is a waste of time and space for both you and the interpreter. The
above is functionally equivalent to
g = validate
and if you want that, you could name the function 'g' when you define it.
>>>l=[]
In some fonts, 'l' and '1' are nearly identical; please use something
else for public code, which you made this to be by posting it;-)
>>>for x in range(1,10):
g(l)
As said, the 'g' wrapper is useless.
addval(l)
Hope this helps.
Terry Jan Reedy
--
David C. Ullrich
In article
<f4************ *************** *******@t54g200 0hsg.googlegrou ps.com>,
ssecorp <ci**********@g mail.comwrote:
>def mod(x,y):
return x.append(y)
>mod([1,2],3) k=[1,2,3] k
[1, 2, 3]
>l = mod(k,4) l k
[1, 2, 3, 4]
>l k==l
False
>mod(k,5) k
[1, 2, 3, 4, 5]
>mod(l,4)
Traceback (most recent call last):
File "<pyshell#2 9>", line 1, in <module>
mod(l,4)
File "<pyshell#1 8>", line 2, in mod
return x.append(y)
AttributeError: 'NoneType' object has no attribute 'append'
>l l=k l
[1, 2, 3, 4, 5]
>i=mod(k,1) i
same stuff but i dont find this intuitive.
You need to read the docs. AList.append(x) does _not_
return AList with x appended. In fact it returns None,
because it wants to be a "procedure" that doesn't return
anything at all, but there is no such thing in Python;
functions and methods that do not explicitly contain
a "return" statement return None.
So when you say "return x.append(a)" you're saying
"return None", which explains the rest of it. You
noticed that the second line of
>l = mod(k,4) l
didn't print anything? That's because the first line
set l to None. If you'd typed "print l" instead of just "l"
you would have seen
>>l = mod(k,4) l None
--
David C. Ullrich
On Thu, 10 Jul 2008 14:09:16 -0400, Terry Reedy wrote:
>>>>>g = lambda x:validate(x)
This is doubly diseased.
First, never write a 'name = lambda...' statement since it is equivalent
to a def statement except that the resulting function object lacks a
proper .funcname attribute.
Using lambda in this way is no more "diseased" than aliasing any other
object. It's a matter of personal preference not to bind a lambda to a
name. Functions, whether created by lambda or def, are first class
objects, and as such there's nothing wrong with binding them to names.
Admittedly, the lack of a func_name attribute can sometimes make
tracebacks harder to understand, especially if you've got many bound
lambdas. But that's no worse than this:
>>def factory(n):
.... def f():
.... return "spam"*n
.... return f
....
>>one_spam = factory(1) two_spam = factory(2) one_spam.func _name == two_spam.func_n ame
True
I'm sure that nobody would argue that using factory functions is
"diseased" because the functions have the same func_name attribute --
even if it does sometimes make it harder to interpret tracebacks:
>>one_spam()
'spam'
>>one_spam('arg ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() takes no arguments (1 given)
So by all means say that you personally don't like to bind lambdas to
names, but don't pretend that it is somehow wrong to do so.
Second, never write a function (with either def or lambda) that simply
returns a function of the argument(s).
I think you need to reconsider the way you say that. By definition,
*every* function simply returns a function of the arguments. That's what
functions do.
The wrapping does nothing! This
is a waste of time and space for both you and the interpreter.
When I was a newbie, I used to write:
def sin(x):
return math.sin(x)
That was before I learned to just do this:
sin = math.sin
But just to prove that you should never say never:
>>import timeit T1 = timeit.Timer("f (1)", """def g(x):
.... return x+1
....
.... f = g
.... """)
>>T2 = timeit.Timer("f (1)", """def g(x):
.... return x+1
....
.... def f(x):
.... return g(x)
.... """)
>>> T1.repeat()
[0.5084819793701 1719, 0.5457341670989 9902, 0.5476710796356 2012]
>>T2.repeat()
[0.8854699134826 6602, 0.8981158733367 9199, 0.9578509330749 5117]
So that's a good reason to wrap a function in another function -- to
measure the overhead of a function call.
*wink*
--
Steven This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Oliver Fromme |
last post by:
Hi,
I'm trying to write a Python function that parses
an expression and builds a function tree from it
(recursively).
During parsing, lambda functions for the the terms
and sub-expressions are constructed on the fly.
Now my problem is lazy evaluation. Or at least I
think it is. :-)
|
by: Stephen Thorne |
last post by:
Hi guys,
I'm a little worried about the expected disappearance of lambda in
python3000. I've had my brain badly broken by functional programming
in the past, and I would hate to see things suddenly become harder
than they need to be.
An example of what I mean is a quick script I wrote for doing certain
actions based on a regexp, which I...
|
by: Philip Smith |
last post by:
I've read with interest the continuing debate about 'lambda' and its place
in Python.
Just to say that personally I think its an elegant and useful construct for
many types of programming task (particularly number theory/artificial
intelligence/genetic algorithms)
I can't think why anyone would be proposing to do away with it. Sometimes...
|
by: George Sakkis |
last post by:
I came across a strange error when trying to define a settable property
for a new-style subclass of UserArray (Numeric). Here's a shorter
example that reproduces the problem:
from UserArray import UserArray
from math import hypot
class Vector(UserArray,object):
def __init__(self,x,y):
|
by: Tom Anderson |
last post by:
Comrades,
During our current discussion of the fate of functional constructs in
python, someone brought up Guido's bull on the matter:
http://www.artima.com/weblogs/viewpost.jsp?thread=98196
He says he's going to dispose of map, filter, reduce and lambda. He's
going to give us product, any and all, though, which is nice of him.
| |
by: nobody |
last post by:
Howdy, Mike!
mikecoxlinux@yahoo.com (Mike Cox) wrote in message news:<3d6111f1.0402271647.c20aea3@posting.google.com>...
> I'm a C++ programmer, and have to use lisp because I want to use
> emacs. I've gotten a book on lisp, and I must say lisp is the ugliest
> looking language syntax wise. What is up with this: (defun(foo()).
(DEFUN...
|
by: Peter Oliphant |
last post by:
I'm drawing graphics using the Graphics object one can grab in a Form's
Paint event. But I'm getting a weird thing happening...
These graphic shapes flicker (even if unchanged). UNLESS- I created a timer
and had the timer update a Label on the form with timer interval set to 10.
Now all the shapes I draw in the Paint event of the form draw...
|
by: rubbishemail |
last post by:
Hello,
I need your help understanding lambda (and doing it a better way
without).
f = lambda x : x*x
# this is a list of functions
|
by: Xah Lee |
last post by:
Python, Lambda, and Guido van Rossum
Xah Lee, 2006-05-05
In this post, i'd like to deconstruct one of Guido's recent blog about
lambda in Python.
In Guido's blog written in 2006-02-10 at
http://www.artima.com/weblogs/viewpost.jsp?thread=147358
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...
| |