Reputation: 11
Some similar questions have been answered here, but they all pertain to using a list as a variable within the function. I am looking to use a list as the function definition:
varlist = ('a',
'b',
'c',
'd',
'e')
def func(*input):
output = ""
for item in input:
output += item
return output
a = "I'll "
b = "have "
c = "a "
d = "cheese "
e = "sandwich."
print func(*varlist)
This returns abcde
, when I'm trying to get I'll have a cheese sandwich.
In other words, the function is using the values from the list as the inputs, rather than using them as variables, which I define below. Of course, when I redefine:
def func(a,b,c,d,e):
output = a+b+c+d+e
return output
and define a
through e
I get the correct output.
The code above is a gross oversimplification, but here's the goal: I am hoping to be able to remove d
from my list (or add f
to my list), and have it tell me I'll have a sandwich.
(or I'll have a cheese sandwich, please.
) without having to redefine the function each time I need to handle a different number of variables. Any thoughts are much appreciated.
Upvotes: 0
Views: 6460
Reputation: 1
Here is the simplest version I can come up with.
varlist = ('a', 'b', 'c', 'd', 'e')
def func(inp):
return " ".join(inp)
a = "I'll"
b = "have"
c = "a"
d = "cheese"
e = "sandwich"
print(func(map(eval, varlist)))
Upvotes: 0
Reputation: 875
Your code gets pretty close, but you seem to bee missing some key concepts. When you create the varlist with the strings, they don't automatically refer to the objects you define below. You have to evaluate them. If you trust the source you can just use eval(), but if they user will input it, you might want to do something else. Also, there is no need to unpack the list, just leave it as is. And don't name stuff in python the same name as builtins, in either version. Here is what I wrote with those changes.
varlist = ('a','b','c','d','e')
def func(inp):
output = ""
for item in inp:
output += item
return output
a = "I'll "
b = "have "
c = "a "
d = "cheese "
e = "sandwich."
print func(map(eval, varlist))
Upvotes: 0
Reputation: 37319
args = (a, b, c, d, e) # not ('a', 'b', 'c', 'd', 'e')
func(*args)
Upvotes: 1