Home > database >  How to create a list of named lists in Python?
How to create a list of named lists in Python?

Time:12-24

I need to create a list of named lists, so that I can iterate over them. This works, but I'm wondering if there isn't a better way.

terms = []; usedfors = []; broaders = []; narrowers = []
termlist = [terms, usedfors, broaders, narrowers]

The reason for doing it this way is that I have a function do_some_list_operation(l) and I want to do something like

for i in termlist:
    do_some_list_operation(i)
    

rather than

do_some_list_operation(terms)
do_some_list_operation(usedfors)
do_some_list_operation(broaders)
do_some_list_operation(narrowers)

I've been searching for 'how to build list of named lists' to no avail.

CodePudding user response:

The way you are doing it is fine but be aware that you are creating a list of lists when you defined termlist. If you want to have the name of the lists then termlist should be:

termlist = ["terms","usedfors", "broaders", "narrowers"]

Now if you want to use these strings as list names you can use globals() or locals() e.g.:

terms = [1]; usedfors = [2]; broaders = [3,4,8]; narrowers = [5]
termlist = ["terms","usedfors", "broaders", "narrowers"]

for i in termlist:
    print(sum(locals()[i]))

output:

1
2
15
5
  • Related