Christian Witts wrote: > On 2012/04/12 06:42 AM, john moore wrote: >> Hello Pyhton World, >> >> I'm new at this and was wondering how I create a number of user specified >> lists? >> >> Example: >> >> "How many list would you like to create?" >> User inputs 5 >> creates five lists, >> list1 [] >> list2 [] >> list3 [] >> list4 [] >> list5 [] >> >> I can create one with append, but I don't know how to loop it to create >> five different named list..
> You can use vars() to create the variables on the fly. vars() is just a > dictionary containing the variable name as the key, and the data as the > value so you can do `vars()['list1'] = []` and it's easy enough to > create them en masse > > # Set the start to 1, and add 1 to what the user inputted > # as range/xrange doesn't include the top number > for i in xrange(1, user_input + 1): > vars()['list%s' % i] = [] This will stop working once you move your code into a function: >>> def f(): ... vars()["list1"] = ["a", "b"] ... print list1 ... >>> f() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in f NameError: global name 'list1' is not defined I recommend that you bite the bullet and use a dedicated dictionary or list to hold your five lists from the very begining: >>> num_lists = int(raw_input("How many lists? ")) How many lists? 5 >>> list_of_lists = [[] for i in range(num_lists)] You then have to access the first list as "list_of_list[0]" instead of "list1" and so on: >>> list_of_lists[0].append(1) >>> list_of_lists[4].append(2) >>> list_of_lists [[1], [], [], [], [2]] _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor