0

I want a line of code which will create an empty list whose name is determined by an incrementing variable.

Everywhere I've looked thus far has been unhelpful. They suggest instead something which makes a list of empty lists or using a dictionary. This is not what I want, I want a line (or several) of code which just creates an empty list (which is not part of a dictionary or a list of lists, a stand alone entity). I want these lists to be distinct, distinguished by a variable which increments by 1 every time a new empty list is created.

These empty lists can't be made in one batch at the very beginning as I intend to make and delete these lists throughout a recursive function. I need to make multiple lists as my intention is for this function to descend to a new level of recursion but return later to the previous list. These are acting as temporary working lists which calculate a value for each item of an original list and then copy the result into a final list once it is found.

str("list_" + i) = []

If i = 1, then I would like this line of code to create an empty list with the name "list_1" which I can proceed to interact with throughout my script.

Instead I'm met with "SyntaxError: can't assign to function call"

By all means let me know if I'm not making any sense at all and I will do my best to convey my request.

7
  • You know that there's a reason that people are suggesting anything other than what you want? You want a variable number of variables (which is the dupe for this) and it just creates horrible code that can't be followed properly. Commented Jan 27, 2019 at 23:20
  • 3
    honestly a defaultdict(list) sounds ideal even though you say it is not Commented Jan 27, 2019 at 23:20
  • while this approach is probably technically possibly, i would advise against it. there are far easier ways to get a list of lists Commented Jan 27, 2019 at 23:20
  • I'll assume that you're a new Python developer, in which case, welcome! It sounds like what you want is inconvenient to manage though. I'm not convinced it's a good idea, and would heavily suggest using dictionaries for this purpose Commented Jan 27, 2019 at 23:24
  • Are you sure that your recursive algorithm can't work just with lists in local variables? If you do something like local_list = [] in the body of the function, that will create a separate empty list each time the function is called. It won't share the list with the other calls, either earlier or later, unless you write code to make it do so. Dealing with local variables is much nicer than using globals. Commented Jan 27, 2019 at 23:43

3 Answers 3

1

Highly advise against this but this achieves what you want depending on your use case:

globals()['list_' + str(i)] = []

for i in range(5):
    globals()['list_' + str(i)] = []

list_1
[]

list_2
[]

etc...

Depending on your use case switch globals for locals and vice-versa.

A better idea would be defaultdict

from collections import defaultdict

my_lists = defaultdict(list)

Now you don't have to initialize any list until you use it and every key comes with it's value being a list already. For example:

for i in range(5):
    my_lists['list_' + str(i)].append('foo')

my_lists

defaultdict(list,
            {'list_0': ['foo'],
             'list_1': ['foo'],
             'list_2': ['foo'],
             'list_3': ['foo'],
             'list_4': ['foo']})
Sign up to request clarification or add additional context in comments.

4 Comments

This is the least Pythonic, correct answer to a Python question I've ever seen. Strongly suggest the defaultdict solution!
pretty sure the code shows you exactly how to do that in a loop
Yeah I'm dumb don't worry sorry for asking a stupid question
In my opinion, the globals solution should be removed or demoted to a comment. Really, defaultdict is the only recommended solution.
0

This is bad practice but anyway:

for i in range(10):       # for global vars
    globals()["list_" + str(i)] = []
print(list_0) # []

Maybe what you're looking for is a dictionary:

items = dict()
for i in range(10):       # for dictionary 
    items[str("list_" + i)] = []
print(items.list_0) # []

6 Comments

This is incorrect in several ways. item[str("list_" + i)] = [] but item doesn't exist, that's a typo, and I don't understand the point of MyClass because it's not even properly defined
1. How to set global attributes 2. How to set object properties 3. why you might want to use a dictionary.
Of course don't use the object if you don't have an object, maybe I should have made that clearer
Ok, and how does completely invalid code do any of those? This just throws errors.
This was misleading and I removed it completely, thanks for the feedback
|
0

Avoid globals, use defaultdict

Using a collections.defaultdict is both efficient and manageable. You don't need to add keys explicitly when appending to list values:

from collections import defaultdict
dd = defaultdict(list)
dd['list_0'].append('foo')

print(dd)
# defaultdict(<class 'list'>, {'list_0': ['foo']})

If you want to explicitly add keys, even with empty list values, you can do so by feeding an extra argument:

from collections import defaultdict
dd = defaultdict(list, **{k: [] for k in [f'list_{i}' for i in range(5)]})

print(dd)
# defaultdict(<class 'list'>, {'list_0': [], 'list_1': [], 'list_2': [],
#                              'list_3': [], 'list_4': []})

Comments

Your Answer

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