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?

5
  • I'm not entirely sure what you're asking here. Are you talking about a list of lists? Commented Apr 4, 2013 at 23:27
  • This is unclear... what is list(1), list(2), etc? ... I have a feeling we're heading for a list-comp .... Commented Apr 4, 2013 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. Commented Apr 4, 2013 at 23:29
  • 1
    I think this is the same question as: stackoverflow.com/questions/2488457/… Commented Apr 4, 2013 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. Commented Apr 4, 2013 at 23:42

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

3 Comments

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 ?
can also use the locals() and globals() functions, will update the above answer
''.join(['list', str(i)]) == 'list' + str(i). Also it's vars() not var(). Also 'list{}'.format(str(i)) == 'list{}'.format(i)

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.