0

I want to make a while loop kind of like this

list=[]    
while x in range(r):
        list-x="something"

Where each time the loop begins it makes a new list with number (x). So if it loops over 5 times there will be different lists: list(1) list(2) list(3) list(4). '

Is this even possible?

user1985351
  • 4,589
  • 6
  • 22
  • 25
  • I'm not entirely sure what you're asking here. Are you talking about a list of lists? – Blender Apr 04 '13 at 23:27
  • This is unclear... what is `list(1)`, `list(2)`, etc? ... I have a feeling we're heading for a list-comp .... – mgilson Apr 04 '13 at 23:28
  • I think he/she wants to make `r` number of lists, created dynamically, according to the value of `r`, while naming them `list-1` to `list-r`. – brbcoding Apr 04 '13 at 23:29
  • 1
    I think this is the same question as: http://stackoverflow.com/questions/2488457/how-to-increment-variable-names-is-this-a-bad-idea – Jonathan Clede Apr 04 '13 at 23:34
  • 2
    Instead of `list-x` put the list in another list and write `lists[x]`. Don't use variable names to encode data, it's pointless. – Jochen Ritzel Apr 04 '13 at 23:42

1 Answers1

4

You are able to do this with the vars() function:

for i in range(5):
    list_name = ''.join(['list', str(i)])
    vars()[list_name] = []

You can then reference each list:

print(list1)
--> []
print(list2)
--> []

etc...

You can also achieve this using the locals() or globals() functions as below:

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

Hope that helps!

Nick Burns
  • 973
  • 6
  • 4
  • I don't succeed in findind a link in the pythondocs or on google about that `var()` function. Can you pick a link that talks about it, or explain about it a little here ? – Stephane Rolland Apr 04 '13 at 23:37
  • can also use the locals() and globals() functions, will update the above answer – Nick Burns Apr 04 '13 at 23:43
  • `''.join(['list', str(i)]) == 'list' + str(i)`. Also it's `vars()` not `var()`. Also `'list{}'.format(str(i))` == `'list{}'.format(i)` – jamylak Apr 05 '13 at 07:09