1

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.

3
  • 2
    What do you mean by a named list? Do you mean a dict perhaps? Commented Dec 23, 2021 at 17:14
  • Your for loop looks good to me as is at the moment. unless your termlist is strings like termlist = ["terms", "usedfors", "broaders", "narrowers"] Commented Dec 23, 2021 at 17:19
  • @msaw328 By named lists I mean each name should reflect what's in them, rather than mylist[0], mylist[1], etc. I chose list because they need to be an ordered collection of strings. I'd use dict or OrderedDict for key-value pairs. Commented Dec 23, 2021 at 20:21

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

While I like the answer by @jayvee and upvoted it, I think a more conventional answer would be one based on using a dictionary as first suggested by @msaw328.

Starting with our new data structure:

term_data = {
    "terms": [1],
    "usedfors": [2],
    "broaders": [3, 4, 5],
    "narrowers": [6, 7]
}

Perhaps like:

for term in term_data:
    print(f"{term} sums to {sum(term_data[term])}")

or even

for term, term_value in term_data.items():
    print(f"{term} sums to {sum(term_value)}")

Both should give you:

terms sums to 1
usedfors sums to 2
broaders sums to 12
narrowers sums to 13

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.