-1
def my_function(x, y, z):
    mini = min(x,y,z)
    return mini

a = 78*453
b = 654-877
c = 98765*785

print(my_function(a,b,c))

I'm learning about functions in Python, and I'm wondering how can I return the variable name rather than it's value in this code. I know the variable b (which is assigned to the local variable y) has the minimum value, but how can I print "b" or "y" instead of '-223' based on that?

globglob
  • 143
  • 8
  • 2
    `my_function()` *did not receive any variables* - it received only numeric values, with absolutely no connection to the variables that held them. It could return something like `"first"`, `"second"`, `"third"` to indicate which value was smallest, but it couldn't possibly return `"a"`, `"b"`, `"c"` because it has no way of knowing those names. – jasonharper Oct 16 '19 at 13:46

3 Answers3

1

You could pass a dict as a parameter to your function, and set the variable names as the dict keys like this:

d={'a': 78*453, 'b': 654-877, 'c': 98765*785}

and then get the key name with the min value like this:

def my_function(d):
    return min(d, key=d.get)
1

Even though its probably not advisable, but since python 3.8 you could work with the new = in f-strings. Take this example:

def return_value(a):
    return a

def return_variable_name_with_value(a):
    return f'{a=}'

print(return_value(5))
# Output:
# 5
print(return_variable_name_with_value(5))
# Output:
# a=5
Kevin Müller
  • 722
  • 6
  • 18
1

min() will find minimum value, so it doesn't care about argument name. But min() can take also iterable as argument.

data = [2, 3, 1]
print(data.index(min(data))

With this you will get position of minimum value.

You can also use more sophisticated approach - store some metadata, like name with data:

data = [('a', 3), ('b', 0), ('c', 1)]

here you have list of tuples, but to find min value you have to let know min what value use for comparison:

minValue = min(list(map(lambda x: x[1], data)))
minPosition = list(map(lambda x: x[1], data)).index(minValue)
print(data[minPosition]) # prints ('b', 0)

Searching for variable name directly is not advised, someone may refactor something later and your code will be broken. It's better to store more information as data.

3mpty
  • 1,354
  • 8
  • 16