0

I am trying to return a function but as list NAME, in another function should accept a list but it seems it return string into the second function

choices = ['a', 'b','c']
a = ['1','2','3']
b = ['4','5','6']
c = ['7','8','9']
choices = tuple(choices)
def let_user_pick(choices):
    print("Please choose:")
    for idx, element in enumerate(choices):
        print("{}) {}".format(idx+1,element))
    i = int(input("Enter number: "))

    if 0 < int(i) <= len(choices):
        return choices[i-1]

def a2_only(data):
    print(data)

a2_only(let_user_pick(choices))

so I need to run the second function as below (logically calling a list not string)

a2_only(c) NOT a2_only('c')

Current ouput:

Please choose:
1) a
2) b
3) c
Enter number: 3
c

expected ouput:

['7','8','9']
the small
  • 67
  • 6
  • Does this answer your question? [Convert string to variable name in python](https://stackoverflow.com/questions/19122345/convert-string-to-variable-name-in-python) – tafaust May 05 '20 at 05:10

4 Answers4

2

Use globals to access dict of the current variables scope. Something like this

choices = ['a', 'b','c']
a = ['1','2','3']
b = ['4','5','6']
c = ['7','8','9']
choices = tuple(choices)
def let_user_pick(choices):
    print("Please choose:")
    for idx, element in enumerate(choices):
        print("{}) {}".format(idx+1,element))
    i = int(input("Enter number: "))

    if 0 < int(i) <= len(choices):
        c = choices[i-1]
        return globals().get(c)

def a2_only(data):
    print(data)

a2_only(let_user_pick(choices))
Anton Pomieshchenko
  • 2,051
  • 2
  • 10
  • 24
  • thanks a lot that works I changed a bit in the code and still working fine return globals().get(choices[i-1]) – the small May 05 '20 at 05:00
  • Usage of `globals` is however very bad in any programming language, see this SO thread: https://stackoverflow.com/questions/19158339/why-are-global-variables-evil – tafaust May 05 '20 at 05:01
2

You could change the first few lines to be

a = ['1','2','3']
b = ['4','5','6']
c = ['7','8','9']
choices = [a, b, c]

That way you are putting the lists in the list instead of the names of the list.

Hasan
  • 200
  • 2
  • 12
1

There already is an excellent answer by @JuanPotato; however, you could also use a python dict here:

a = ['1','2','3']
b = ['4','5','6']
c = ['7','8','9']
choices = {'a': a, 'b': b,'c': c}
keys = ['a', 'b', 'c']

def let_user_pick(choices):
    print("Please choose:")
    for idx, element in enumerate(keys):
        print("{}) {}".format(idx+1,element))
    i = int(input("Enter number: "))

    if 0 < int(i) <= len(choices.keys()):
        return choices.get(keys[i-1])

def a2_only(data):
    print(data)

a2_only(let_user_pick(choices))

# Please choose:
# 1) a
# 2) b
# 3) c
# Enter number: 3
# c
# ['7', '8', '9']

If the order is important, have a look at pythons OrderedDict.

Here is a repl.it if you want to test it yourself: https://repl.it/repls/CylindricalDecentDriverwrapper

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
tafaust
  • 1,457
  • 16
  • 32
  • the idea that i have to update choices manually each time based on lists given, but whatever lists i have i run for loop append to choices and second function will run without any intervention imagine now i have a,b,c lists after an hour i have a,b,d,f – the small May 05 '20 at 05:04
  • @thesmall You could as well create your `choices` dict from any given key value pair. It is not enough to simply extend the `choices` list without any values attached to them, right? You can as well write your own function to recreate the `choices` dict from the keys and the values. However, I'd suggest using a python dict right away to have the correct choice to value mapping. – tafaust May 05 '20 at 05:08
1

Your code is a mess. You are hiding the actual end output from the user. When they see 1) a and they press 1, why would they expect the return to be ['1', '2', '3']?

Also, what is the point of the a2_only() function if it's just a limited form of the built-in print() function?

I would rewrite the code as the following, which I think makes more sense:

def let_user_pick(choices):
    print("Please choose:")
    for _ in choices:
        print("{}) {}".format(_, choices[_]))

    choice = input("Enter choice: ")

    try:
        return choices[choice]
    except KeyError:
        return "Invalid option!"


options = {
    'a': ['1', '2', '3'],
    'b': ['4', '5', '6'],
    'c': ['7', '8', '9']
}

print(let_user_pick(options))

BTW: I know this technically isn't what you are looking for. Anton Pomieshchenko has already provided a direct answer to your question. You can also see this answer by StefanW that shows how you can change variables as strings through the exec() function. However, that is highly frowned upon and considered to be bad coding style.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
YulkyTulky
  • 886
  • 1
  • 6
  • 20