[Tutor] user created lists

Christian Witts cwitts at compuscan.co.za
Thu Apr 12 09:25:53 CEST 2012


On 2012/04/12 08:59 AM, Peter Otten wrote:
> 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:
You could use globals() then instead of var(),  although it's a 
do-it-at-your-own-risk situation then if you overwrite built-ins and 
other functions in the namespace.  Creating your own dictionary with the 
'variable name' as the key, would be the nicer solution instead.

-- 

Christian Witts
Python Developer
//
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120412/dfd5e394/attachment.html>


More information about the Tutor mailing list