"Burn in" a global variable on function definition [duplicate] - python

This question already has answers here:
Read/Write Python Closures
(8 answers)
Local variables in nested functions
(4 answers)
Closed 5 years ago.
What is the way to "burn in" an external variable to a function upon definition?
funcs = []
for n in range(5):
def f(x):
return n * x
funcs.append(f)
del n
But trying
[g(2) for g in funcs]
or
funcs[1](2)
Gives an error
NameError: name 'n' is not defined
Is there a way to allow defining a function with a parameter which will become fixed for the function scope?

Related

Is there a bug in numpy when using the += operator [duplicate]

This question already has answers here:
What is the difference between i = i + 1 and i += 1 in a 'for' loop? [duplicate]
(6 answers)
When is "i += x" different from "i = i + x" in Python?
(3 answers)
Understanding Python's call-by-object style of passing function arguments [duplicate]
(3 answers)
How do I pass a variable by reference?
(39 answers)
Closed 3 years ago.
When using a function in phyton, I am taught that actually a copy of my value is parsed. In the example shown below apply a function onto a Parameter a. Here, I expected that a copy of a is sent to the function fun. In this function, only the copy of a is available, not parameter a on a global scope. I even gave it another Name: b. When I modify the value b in my function, then also the Parameter a on the global scope is changed. Is this supposed to be correct?
import numpy as np
def fun(b):
b += np.array([1,1])
a = np.array([1,1])
fun(a)
print(a)
I expected to get np.array([1,1]), but I get np.array([2,2])
This happens only, when I use the += Operator in the function fun. If I use b = b + np.array([1,1]) instead, the value of a on global scope stays the same.
When you call fun() you don't make a copy of a and modify b, rather, a itself is passed to fun() and refered to as b in there.
As such,
b += np.array([1,1])
modifies a.
In python the list datatype is mutable, that means that every time you run your function, a list will keep growing.
The key moment is here: b += np.array([1,1])
You already got a, which is [1, 1] and you adding it to another array which is [1, 1] and you are getting [2, 2] which is how it should be.
You are ending up modifying the a

How to create a list of functions using one function with different arguments? [duplicate]

This question already has answers here:
Creating functions (or lambdas) in a loop (or comprehension)
(6 answers)
Closed 3 years ago.
I'm trying to build a list of functions [f1(), f2(), ..., fn()] defined by the same function but with different arguments.
For example, let say f(x,i) and the goal is to define the list [f1(), f2(), ..., fn()] where fi(x) = f(x,i).
I've already tried on Python 3 the code below:
F=[]
for i in range(5):
f = lambda x:x+i
F.append(f)
or
G=[0]*5
for i in range(5):
G[i]=lambda x:x+i
And then, by printing these built functions with x=0
print([F[i](0) for i in range(5)])
print([G[i](0) for i in range(5)])
But I get [4,4,4,4,4] instead of [0,1,2,3,4].
From what I understand, the way I'm trying to build the list is wrong because the change of the i value impacts all functions previously defined. So, how to avoid it?
Thank you!
Use functools.partial:
from functools import partial
def foo(x, y):
return x + y
funcs = [partial(foo, i) for i in range(10)]
for f in funcs:
print(f(10))

How does the closure operate in returning function when using circulating variables? [duplicate]

This question already has answers here:
What do lambda function closures capture?
(7 answers)
Creating functions (or lambdas) in a loop (or comprehension)
(6 answers)
Closed 4 years ago.
def count():
fs = []
for i in range(1, 4):
def f():
return i*i
fs.append(f)
return fs
f1, f2, f3 = count()
print(f1(), f2(), f3())
I'm learning Python, finding the result above is 9 9 9 instead of 1 4 9. I try to debug the code step by step, but in IDE I cannot get any extra information about <function count.<locals>.f at 0x0000000003987598> when appending functions to list. I wanna know what is the detail order of the code, especially when appending f() whether the value of the variable i would be recorded(i*i or 1*1 or some other circumstance). And what 's the significance of for i in range(1, 4)?

Using a variable outside of a defined function [duplicate]

This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 6 months ago.
If I had a function that I made:
def a():
n = 2*2
How could I access n out of the function without calling a?
You cannot. You will need to define the variable outside of the function, or call the function and return it.
You need to return it, so do:
def a():
n = 2*2
return n
print(a())
Output:
4
You can also do print, but return is better, check this: What is the formal difference between "print" and "return"?

Python variables outside function [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
Closed 7 years ago.
I'm trying to access the counter variable in my function, why doesn't it work and how do I resolve it?
Relevant code:
sum = 0
counter = 0
def newFibo(a, b) :
if(counter > 4000000) :
return
c = a + b
sum += c
counter +=1
newFibo(b,c)
newFibo(1,2)
print(sum)
error: "local variable 'counter' referenced before assignment"
In Python, if you want to modify a global variable inside a function, you have to declare it as global inside the function:
def newFibo(a, b) :
global counter, sum
..............
Note that you don't need it if the variable is only read inside the function but not modified.
You need to use the keyword global to tell python that a variable is outside the current function.
So, basically, add global sum, counter right after def newFibo(a, b):.

Categories

Resources