Python Forum

Full Version: How to access arguments by name from function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I have function in which I am passing multiple lists. Now, I want to access (or assign to another variable) the lists (given as arguments in function) by its name. I tried below code, but its giving error.

#%% passing multiple lsit to function
def my_func(list1,list2,list3):
    return list1,list2,list3
p1 = my_func(list1 = ['BNKL', 'KPUI', 'HYNI'],\
             list2 = ['Ty'],\
                  list3 = [6, 7, 8])
print(" The first list : ", p1[0])
print(" The second list : ", p1[list1])
l_l1 = p1[1]
Error:

The first list :  ['BNKL', 'KPUI', 'HYNI']
Traceback (most recent call last):

  File "<ipython-input-2-30d2f38dbdd7>", line 6, in <module>
    print(" The second list : ", p1[list1])

NameError: name 'list1' is not defined
Names defined in the function are only available in the function. If you need them outside the function, return a dictionary:

def foo(list1, list2, list3):
    return {'list1': list1, 'list2': list2, 'list3': list3}
#%% passing multiple lsit to function
def my_func(list1,list2,list3):
    return {'list1': list1,'list2':list2,'list3': list3}
p1 = my_func(list1 = ['BNKL', 'KPUI', 'HYNI'],\
             list2 = ['Ty'],\
                  list3 = [6, 7, 8])
print(" The second list : ", p1['list2'])
print(" The first list : ", p1[0])
Error: Can't we acess by index?

The second list : ['Ty']
Traceback (most recent call last):

File "<ipython-input-7-9fcbb5cddfc7>", line 6, in <module>
print(" The first list : ", p1[0])

KeyError: 0
Not with a dictionary. You could use a named tuple, but before I went that far I would ask if I really needed to access by both.
Does it seem if we give in list format, then we can not access list by index?
You can get it by index if you return the values as a nested list

def my_func(list1,list2,list3):
    return [list1,list2,list3]
p1 = my_func(list1 = ['BNKL', 'KPUI', 'HYNI'],\
             list2 = ['Ty'],\
                  list3 = [6, 7, 8])

print(" The first list : ", p1[0])
Sir/Madam,
my apologies, I am still confused, for example: from the nested list, we can not access by name, but only access by index. In the previous answer below, we can only access by name. This conclusion is correct? or can we make it flexible that we can either access by index or by name?
def my_func(list1,list2,list3):
    return {'list1': list1,'list2':list2,'list3': list3}
(Sep-19-2019, 03:06 PM)SriRajesh Wrote: [ -> ]can we make it flexible that we can either access by index or by name?

As I said, you would need to use a namedtuple. But why do you need to access it both ways? It creates an inconsistency, and inconsistencies cause problems down the road. It might be better to change how you are using the data than to change the data.