How to pass a specific value from Tuple into a function [duplicate] - python

This question already has answers here:
Getting one value from a tuple
(3 answers)
Closed 2 years ago.
variable1 = 1
variable2 = 2
a_tuple = (variable1, variable2)
def my_function(a):
pass
my_function(a_tuple(variable1))
Is there a way I can pass a specific value from a tuple into a function? This is a terrible example, but all I need to know is if I can pass variable1 from the tuple into the function, I understand in this instance I could just pass in variable 1, but its for more complicated functions that will get its data from a tuple, and I don't like the look of that many variables, too messy.
variable1 = 1
variable2 = 2
a_tuple = (variable1, variable2)
def my_function(a):
pass
my_function(*a_tuple)
This code would obviously provide an error as it unpacks the tuple and inserts 2 variables, to make this work in my program I would need a way to pass either variable1 or variable2 into the function. My question is can I define exactly which items from a tuple are passed into the function when calling the function? Latest version of Python if it matters.
P.S. I wrote print("hello world") for the first time 7 days ago, this is my first language and my first question I couldn't find an answer to. Go easy on me, and thank you for your time.

In the code you provided you don't have a tuple you have a list. But it is still pretty much the same.
In your example lets say that you wanted to pass the first variable you would do it like this:
my_function(a_tuple[0])
If you don't understand why there is a zero here and how does this work I highly suggest learning about lists before functions.

You just need to access individual elements of the tuple, using index notation:
my_function(a_tuple[0])
or
my_function(a_tuple[1])
You could, if you wanted, write a new function which takes a tuple and an index, and calls my_function with the appropriate element:
def my_other_function(tuple, index):
return my_function(tuple[index])
But I don't see how there would be much gain in doing that.

you can index a tuple or use the index method.
def my_function(a):
pass
my_function(a_tuple[0])
if you want to get the index of a value use the index() method
a_tuple.index(variable1) #this will return 0

Related

Is there a way to change the name of a variable in a function in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm trying to do something like this:
def func(varname):
varname = 1
func(x)
print(x)
But I get NameError: name 'x' is not defined
No, the syntactical construct you seem to be interested in is not possible. The reason is that function parameters are copies of the value (or reference) of the variable you pass in. Changing the value (or reference) of varname cannot change the value (or reference, for mutables) of x.
Now, the behavior that you want is totally possible. As a general rule, in order to have a function create a value and then assign that value to a variable name of your choice you use a return statement:
def funcname():
return 1
x = funcname()
print(x)
You need to declare the thing you are putting into the function as a parameter.
You should also actually do something with the value you are changing in the method.
In your example
def func(varname):
varname = 1
return varname #Return whatever you do to the input
x=3
x =func(x) #Do something with the value returned from your method
print(x)
Mostly the information you get back from a function is what is given in the return value. It's possible, even common, for functions to make changes in mutable data structures that they are passed (e.g. a list), especially where this is capturing state information or updating on the basis of other information handled by the function. And if you rearrange the contents of a list, the list elements will certainly have different values when the function exits.
Certainly you could do this:
def square_it(varname):
return varname*varname
x = square_it(3)
print(x)
giving output of 9, of course. You can also assign x to something else so that they now both have the same value
y = x
x = square_it(y)
which in some senses "changes the name" of what is referring to the value 9 to y, and moves x on to refer to something else.

Use variable name, not its value [duplicate]

This question already has answers here:
How can you print a variable name in python? [duplicate]
(8 answers)
Closed 2 years ago.
What?
I want to use a variable's name, not it's value. For instance, in the following example, I would like the function to return my_list[1] , and not B..
my_list = ['A', 'B']
def example(list_element):
print(repr(eval(list_element)))
example(my_list[1]) # I would like this to print `my_list[1]`
But Why?
I am trying to create a function that takes a given element from a list, and also uses the previous list element. By getting the name my_list[1], I can subtract one and also get my_list[0]. Once I have both the names, I can utilise the values stored under these names.
Yes, I could simply add two fields to the function and put them in each time but I was hoping to keep the body of my code a little easier to read.
Don't use data to manipulate your code, it's not how Python (or most languages) works.
To do what you're trying to do:
my_list = ['A', 'B']
def example(a_list, index):
print('The element passed: ', a_list[index])
print('The element before it: ', a_list[index-1])
example(my_list, 1)
Of course this doesn't check if you didn't accidentally pass 0, etc. - but it shows you don't need to make a mess with eval, exec, etc.

Having difficulty understanding how function works [duplicate]

This question already has answers here:
Return multiple values over time
(2 answers)
Closed 5 years ago.
I've written a function in python to see If i know what I'm doing but unfortunately I'm not. I thought my defined arg variable will hold a number and multiply each of the numbers which *args variable holds and print it all at a time. But, it is giving me the first result only.
This is what I've written:
def res_info(arg,*args):
for var in args:
return var*arg
print(res_info(2,70,60,50))
Having:
140
Expected:
140
120
100
I don't understand why I'm not getting all the results. Thanks for taking a look into it.
You are on the right path. The problem you had was due to your use of the return statement. Use yield instead.
>>> def res_info(arg,*args):
for var in args:
yield var*arg
>>> list(res_info(2,70,60,50))
=> [140, 120, 100]
So, what was happening was, even though your logic was correct, since there was a return statement in the loop, your loop hence was never fully executed and your program scope would come out on the first iteration of the loop itself (ie, when var = 70).
Using yield, solved the problem as it returns a Generator object after all calculations, and hence does not exit the loop like return does.
def res_info(arg,*args):
result = []
for var in args:
result.append(var*arg)
return result
print(res_info(2,70,60,50))

Python calling function by string name from code [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 7 years ago.
Here is what I would like to be able to do:
I have a file called functions, with lots of functions. The functions are all essentially the same, functionally speaking (i.e., they are all of the form: pandas.Dataframe -> pandas.Dataframe). Obviously, they do different things to the Dataframe, so in that sense they are different.
I'd like to be able to pass my main function a list of strings, which would be the actual function names in the module, and have my program translate the strings into function calls.
So, basically, instead of:
functions = [module.functionA, module.functionB, module.functionC]
x = g(functions)
print(x)
> 'magical happiness'
I would have:
function_strings = ['functionA','functionB','functionC']
functions = interpret_strings_as_function_calls(module,function_strings)
x = g(functions)
print(x)
> 'magical happiness'
Is there a way to do this? Or do I need to write a function in the module that matches each string with it's corresponding function? i.e.:
def interpret_strings(function_string):
if function_string == 'functionA':
return module.functionA
elif function_string == 'functionB':
return module.functionB
etc.
(or in a switch statement, or whatever)
You can use getattr(module, function_string).

Are Python arguments passed by reference? [duplicate]

This question already has answers here:
How do I pass a variable by reference?
(39 answers)
Closed 7 years ago.
In detail, my question is this:
Given the following code,
x = 10
def func(x):
x = x+1
def main():
print(x)
func(x)
print(x)
if __name__ == '__main__':
main()
On running this I get:
10
10
Does this mean that Python does not pass values by reference?
And I did check through the other question of the sort, and most(if not all) included analogies of lists or other such examples.
Is it possible to explain this in simple terms, like just a simple integer?
Ps. I am a beginner to coding.
Thanks
If you are coming from a background such as C or C++, which I did, this can be maddening until you figure it out.
Python has names, not variables, and names are bound to objects. Effectively, you can think of all 'variables' or names, as being pointers to python objects.
In python, integers, floats, and strings are immutable. So when you do the following:
x = 10
x = x + 1
You are first binding the name x to the integer 10, then when you evaluate x + 1 you get a new object 11 and then you bind x to that object. Your x inside the function body is local to the function, and when you bind it to 11, the global x remains bound to 10.
If you were to pass a list to the function, and append something to the list, that list would be modified. A list in python is a mutable object. All names bound to the list would refer to the modified list.
As a result, when you pass mutable objects it may seem as if you are passing by reference, and when you pass immutable objects it may seem like you are passing by value.

Categories