AK9309
AK9309

Reputation: 791

Introducing new variables using a given string

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

Upvotes: 0

Views: 141

Answers (2)

Bob Dylan
Bob Dylan

Reputation: 1833

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.

Upvotes: 2

user1749431
user1749431

Reputation: 569

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"]]

Upvotes: 0

Related Questions