0

I have a list of names my_names = ["A","B","C"] I have a function that can takes each name from a list and returns several lists of information for that name.

def my_function(name):
    return list1, list2, list3

For each name list1, list2, list3 are different.

I want to write a function that wouldn't need any user input but would return a list with 3 lists inside.

def my_function():
    for name in my_list:
        # Part I don't know how to do
        name_list = list1, list2, list3
        # A_list for "A", B_list for "B", C_list for "C"

    return A_list, B_list, C_list

The only thin I don't know is how to make python introduce new empty lists depending on the name in my_list

AK9309
  • 761
  • 3
  • 13
  • 33
  • 1
    Possible duplicate of [How do I do variable variables in Python?](http://stackoverflow.com/questions/1373164/how-do-i-do-variable-variables-in-python) – Morgan Thrapp Oct 19 '15 at 19:11
  • 1
    You will find many posts on this topic. If you really want to stick with this solution, you can use `eval` or `exec` but it is highly recommended to not do that. Use a dictionary ! – Moritz Oct 19 '15 at 19:11
  • I agree a dictionary is best. But you *can* have a list of lists if you want. Just make a main list: `name_list = []` than append each list to it: `name_list.append(list1)`, etc. Then reference each list using its index, then the elements in that list with a secondary index – Bob Dylan Oct 19 '15 at 19:19

2 Answers2

2

A dictionary is best, but you can have a list of lists. Just make a main list: name_list = [] then append each list to it: name_list.append(list1), etc. Then reference each list using its index, then the elements in that list with a secondary index. For example,

def my_function():
    for name in my_list:
        name_list = []
        name_list.append(list1)
        name_list.append(list2)
        name_list.append(list3)
    return name_list

Then if you want to access the second element in the first list from the returned function, you would do so like:

name_list[0][1]

It's hard to say more without knowing more about your problem, but this will work, it's just not optimal.

Bob Dylan
  • 1,773
  • 2
  • 16
  • 27
0

You can create a nested list with n numbers of sublists, where n is any given number of lists

n = 3
nested_list = [[]] * n
# returns [[],[],[]]
#function that takes n, n=3
def create_nested_list(n):
      nested_list = [[]] * n
      return nested_list
nested list = create_nested_list(n)

You can append items in the nested list's lists by indexing, for instancce nested_list[0]=["A"] will append the number "A" to the first sublist, nested_list[1]=["B"]to the second and nested_list[2]=["C"] to the third sublist, so nested_list = [["A"],["B"],["C"]]

user1749431
  • 559
  • 6
  • 21