Posts: 124
Threads: 74
Joined: Apr 2017
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
Posts: 4,229
Threads: 97
Joined: Sep 2016
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}
Posts: 124
Threads: 74
Joined: Apr 2017
#%% 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
Posts: 4,229
Threads: 97
Joined: Sep 2016
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.
Posts: 124
Threads: 74
Joined: Apr 2017
Does it seem if we give in list format, then we can not access list by index?
Posts: 1
Threads: 0
Joined: Sep 2019
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])
Posts: 124
Threads: 74
Joined: Apr 2017
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}
Posts: 4,229
Threads: 97
Joined: Sep 2016
(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.
|