0

How can I create lists using for loop to get list_1, list_2, list_3, etc.? (Python)

I tried this:

for i in range(5):
i += 1
list_(i) = []

But not working.

  File test.py, line 3
runner_(i) = []
            ^

SyntaxError: cannot assign to function call

neznajut
  • 87
  • 3
  • 8
  • What happens when you run your code? What do you expect to happen? As it is in the question you will just get an Indentation Error and it will stop. – JeffUK Nov 15 '20 at 16:01
  • 1
    Does this answer your question? [Dynamic variable name in python](https://stackoverflow.com/questions/2564140/dynamic-variable-name-in-python) – JeffUK Nov 15 '20 at 16:03
  • did you mean to create a dictionary with `{'list_1': [], 'list_2' = []}`? – hiro protagonist Nov 15 '20 at 16:04

9 Answers9

2

You may create list of lists:

main_list = []
for i in range(5):
    sub_list= []
    main_list.append(sub_list)
print(main_list)
print(main_list[0])
1
dic={}
for i in range(5):
    dic[f"list{i}"]= []

print(dic)
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Shad0w
  • 152
  • 2
  • 13
1

Creating multiple variables is not considered Pythonic. If you want to create a series of variables, a good option is to use a list, like so:

list_of_lists = []
for i in range(5)
    list_of_lists.append([])

When you want to access a specific list:

list_of_lists[3]
-> []

However, if you would like to maintain the variable names, you could consider using a dictionary, perhaps like so:

dict_of_lists = {}
for i in range(5):
    dict_of_lists[f'list_{i}'] = []

Accessing:

dict_of_lists['list_1']
-> []
bbnumber2
  • 643
  • 4
  • 18
1

I would strongly recommend you to not do this at all. Creating dynamic variables is rarely a good idea and it might affects performance. You can always use dictionary instead as it would be more appropriate:

lists = {}
lists["list_" + str(i)] = []
lists["list_" + str(i)].append(somevalue)

Look here for some more explanation: Creating a list based on value stored in variable in python

TS_
  • 319
  • 1
  • 5
1

Ideally you should use list or dictionary. But, use the below code for the requirement.

     for i in range(5):
         exec("list_%d = []" % (i+1))
vivek kumar
  • 304
  • 1
  • 8
  • You're correct that the OP most likely needs to use a list or a dictionary. There are almost never a situation where `locals`, `globals` or `exec` is the solution. Using `exec` like this is more of a hack that will lead to confusion and potentially many future problems. – Ted Klein Bergman Nov 15 '20 at 16:51
0

Try with globals():

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

Most awesome, cool and pythonic way is BTW to use a dictionary man ;-)

list_dicts = {}
for i in range(5):
  i += 1
  list_dicts['list_'+str(i)] = []

And retrive/edit like:

list_dicts['list_2']

Tired of the sucking for loop? Time for dict comprehension:

list_dicts = {'list_'+str(i): [] for i in range(5)}
Wasif
  • 14,755
  • 3
  • 14
  • 34
  • There are almost never a situation where `locals`, `globals` or `exec` is the solution. So while `globals` works in this case, it's definitely not the correct approach. It's more of a hack that will lead to confusion and future problems. Your other suggestions are much better. – Ted Klein Bergman Nov 15 '20 at 16:53
0

For this task I would choose a different data structure dict()

This will let You map the keys to respective lists such as:

my_dictionary = {}
for i in range(5):
    my_dictionary[f"list_{i}"] = [] # This might be also my_dictionary["list_"+str(i)]

Please note that I have used empty list as key -> value mapping.

This in turn will produce a following dictionary:

{"list_0": [], "list_1": [], "list_2": [], "list_3":[], "list_4":[]}
Kaszanas
  • 446
  • 4
  • 18
0

I think you are searching for the locals() function, this function holds all the local variables. you could then write something like this.

for i in range(5):
   locals()["list_"+str(i)] = []
Glenn
  • 27
  • 4
  • While it works, it's definitely not the correct approach. It's more of a hack that will lead to confusion. The OP most likely needs to use a list or a dictionary. There are almost never a situation where `locals`, `globals` or `exec` is the solution. – Ted Klein Bergman Nov 15 '20 at 16:49
0

Hope this is your answer

for x in range(5):
    x += 1
    list_name = "list_" + str(x)
    list_item = []
    print("Printing {0} = ".format(list_name), list_item)


Here is output:

Printing list_1 =  []
Printing list_2 =  []
Printing list_3 =  []
Printing list_4 =  []
Printing list_5 =  []
Kamrul Hasan
  • 69
  • 2
  • 14