1

I'm setting up an algorithm and I do not achieve to create a list for each loop index.

I don't know how can I change the names of lists during the for-loop.

for i in range(10):
   list = list.append(1 + i)

In order to get:

list0 = [1]
list1 = [2]
list2 = [3]
and so on.

My objective is to call these lists on another function, is there a way to name these lists with the list index?

I don't have find any subject which describe my issue. Maybe I don't clearly explain my problem.

Bando
  • 1,223
  • 1
  • 12
  • 31

3 Answers3

3

It isn't efficient to create those variables, instead a dictionary would come in handy:

d = {}
for i in range(10):
   d['list%s' % i] = [i + 1]

It actually could be done with:

d = {'list%s' % i: [i + 1] for i in range(10)}
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

To answer your question, you can do this but I think that it is not a best practice for your issue:

for i in range(10):
   locals()['list{}'.format(i)] = [1 + i]

You can see that this code created 10 variables :

>>>print(list0)
[1]
>>>print(list9)
[10]

I'd prefer using a dict as in @U9-Forward answer

Corentin Limier
  • 4,946
  • 1
  • 13
  • 24
0

Instead of doing that assign them all to a reference in another list e.g.

Lst [0] = [1]
Lst [1] = [2]

This is done with:

Lst=[]
for i in range(10):
    Lst.append(i+1)
Jkind9
  • 742
  • 7
  • 24