Question caused by lambda expression in python? [duplicate] - python

This question already has answers here:
How does a lambda function refer to its parameters in python?
(4 answers)
Closed 1 year ago.
I wrote a Python code like:
fun_list = []
for i in range(10):
fun_list.append(lambda : f(i))
for j in range(10):
fun_list[j]()
I want it to output numbers from 0 to 9, but actually it outputs 9 for ten times!
I think the question is that the variable is be transported into function f only it was be called. Once it was be called it will globally find variable named 'i'.
How to modify the code so that it can output numbers from 0 to 9?

Your Code doesn't make sensefun_list[j]() how are you calling a List Element?
If You Want to append the numbers mentioned above into your array then Correct Code is:-
fun_list = []
for i in range(10): ### the range has to be from 0 to 10 that is [0,10)
fun_list.append(i) ### You dont need lambda function to append i
What This does is also if of No need because you first of all havent initialized what is f?... Is it a function?. You here are not appending the value but instead appending the called function statement. You dont need that. Just do it simply like above....:-
fun_list.append(lambda : f(i))

Related

Obtaining a string version of the variable name in Python [duplicate]

This question already has answers here:
Getting the name of a variable as a string
(32 answers)
Closed 1 year ago.
Consider the following code:
x,y = 0,1
for i in [x,y]:
print(i) # will print 0,1
Suppose I wanted instead to print:
x=0
y=1
I realise f-strings can be used to print the intermediate variable name:
for i in [x,y]:
print(f"{i=}") # will print i=0, i=1
However, I am interested in the actual variable name.
There are other workarounds: using eval or using zip([x,y], ['x', 'y']), but I was wondering if an alternative approach exists.
I think this achieves what you want to do -
for i in vars():
print(f'{i}={vars()[i]}')

How can I set a different variable name for each iteration [in python]? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 2 years ago.
NOTE: Please read till the end, I don't want dictionaries.
For example, I have the global variable called var1 and I have the following:
i = 0
for i in range(0, 20):
var1 = i
i += 1
I want to create a new variable called var2 and store the value from the second iteration into that, instead of the initial var1 and so on for every iteration.
I also don't want to store it in some list var and use var[i] for every iteration.
I want the variable names to logically be named for every iteration.
Is there a direct solution or is there any way I can make a variable with the contents of a string?
The main intent of the question is to know if I can generate a new variable for every iteration with naming that has some logic behind it, instead of using lists.
Also, I do not want to define dictionaries as dictionaries have definite sizes and cannot flexibly expand themselves.
You can use exec
The exec() method executes the dynamically created program, which is either a string or a code object.
for i in range(0, 20):
exec("%s = %d" % (f"var{i+1}",i))
print(var1)
print(var2)
print(var3)
print(var4)
print(var18)
print(var19)
0
1
2
3
17
18

How do I make different variables in for loops In Python [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 3 years ago.
I am making a program that has a for loop and every time the loop is ran I want it to make a new variable like
for item in range(0, size)
(Make new variable bit1, bit2, bit3, bit4, etc with value of 0)
Is this possible?
Create a List of variables and append to it like this:
bits = []
for item in range(0, size)
bits.append(0)
# now you have bits[0], bits[1], bits[2], etc, all set to 0
We can do this by appending to the vars() dictionary in the program.
for index, item in enumerate(range(size)):
vars()[f'bit{index+1}'] = 0
Try calling the names now:
>>> bit1
0
And while this works, I'd recommend using a list or a dict instead.

Explain this particular python lambda expression [duplicate]

This question already has answers here:
Accessing elements of Python dictionary by index
(11 answers)
Closed 4 years ago.
Iam trying to learn lambda expressions and came across the below :
funcs = {
idx: lambda: print(idx) for idx in range(4)
}
funcs[0]()
did not understand what is meant by funcs[0] ? Why the index and 0 ?
This is a cool example to show how binding and scope work with lambda functions. As Daniel said, funcs is a dictionary of functions with four elements in it (with keys 0,1,2 and 3). What is interesting is that you call the function at key 0, you expect the index (idx) that was used to create that key to then print out and you'll get 0. BUT I believe if you run this code, you actually print 3! WHAT!?!? So what is happening is that the lambda function is actually not binding the value of 0 when it stores the reference to the function. That means, when the loop finishes, the variable idx has 3 associated with it and therefore when you call the lambda function in position 0, it looks up the reference to the variable idx and finds the value 3 and then prints that out. Fun :)
That was referring more to your question title than to the test... The 0 is to access the function that has key 0 in the dictionary.

python "all" function making list empty [duplicate]

This question already has answers here:
Why can't I iterate twice over the same iterator? How can I "reset" the iterator or reuse the data?
(5 answers)
Closed 4 years ago.
I am new to python and was learning its builtins but function all()
is not behaving as expected i don't know why.Here is my code
n=map(int,input().strip().split())
print(all([j>0 for j in n]))
print(list(n)) #this line returning empty list
Here are my inputs:
1 2 3 4 5 -9
And my output:
False
Does function all changes the original map object(values)? but something like this is not mentioned in given function definition on the docs link.
Thanks in advance
Map returns a generator object which you exhausted in your all function. Therefore when you call list on n, since n is empty/exhausted, it returns an empty list.
To fix just make n a list in the first place.
n=list(map(int,input().strip().split()))
print(all([j>0 for j in n]))
print(n)

Categories