0
names=['abcd','efgh']
nameoflist='names'

def(nameoflist=[]):
    return nameoflist

I want to be able to return the entire list from the function

Ash
  • 1
  • 2
  • Is that related [to this](https://stackoverflow.com/questions/9437726/how-to-get-the-value-of-a-variable-given-its-name-in-a-string)? That's an ugly way of doing things, a little too *magical*, so if it can be avoided, do avoid it. – tadman Jul 19 '17 at 00:50
  • 1
    Sounds like a bad idea... I dunno what you're trying to accomplish, but I bet there's a cleaner way to do it than depending on a variable's _name_ to make it work. – Óscar López Jul 19 '17 at 00:52
  • Please explain what you are trying to accomplish. This is a pretty bad idea, and if you give us an idea of why you want to do this we can recommend a better solution altogether. – SethMMorton Jul 19 '17 at 01:10

2 Answers2

0

Assuming names is global as specified in the question, you can do this

names=['abcd','efgh']
nameoflist='names'

def return_names(nameoflist):
    return globals()[nameoflist]

However, this is pretty ugly, and I'd probably try another way to do it. What do you need the name for? Is there any other way to get the information you're asking for?

rma
  • 1,853
  • 1
  • 22
  • 42
-1

This one way to do what you are asking. But it is not good programming.

names=['abcd','efgh']
def list_by_name(list_name):
  return eval(list_name)
print(list_by_name('names'))

Also, argument list_name should be a string. It should not default to a list, which would make the function to fail if called without argument. It should not have a default value.

Sci Prog
  • 2,651
  • 1
  • 10
  • 18
  • [**Do not ever use `eval` (or `exec`) on data that could possibly come from outside the program in any form. It is a critical security risk. You allow the author of the data to run arbitrary code on your computer.**](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) – Karl Knechtel Jul 05 '22 at 00:27
  • This is exactly why I wrote "it is not good programming" (maybe I should put it in bold). – Sci Prog Sep 28 '22 at 16:44