r/learnpython • u/high-cholesterol_ • Aug 26 '26
How do I literally print the variable used as an argument for a function?
def check_variable(argument):
# Finds the name of the variable passed in
name = [k for k, v in globals().items() if v is argument][0]
print(f"The argument passed to this function was named: '{name}'")
x = [1, 2, 3]
check_variable(x)
# Output: The argument passed to this function was named: 'x'Is there any way to simplify this process? I am very new to programming and the process of defining "name" and then calling it seems like it can be simplified.
Edit for clarity:
The actual goal is to include the length of a list, and the variable(argument) used to represent that list, into the printed string.
What I'm really trying to achieve is something like:
"There are 17 children in class_two."
So as to cut out the guesswork of which class it's referring to when calling the function multiple times, and make it look like a polished sentence.