More about variables

Tom Culliton culliton at clark.net
Thu Apr 6 13:37:03 EDT 2000


What (or maybe what do you think) you are trying to do?  Most likely
you would be better off with just a list or tuple if you're dealing
with and unknown number of data items.  Not everything needs a name,
and there isn't much difference between:

v0, v1, v2, v3, v4, v5

and

v[0], v[1], v[2], v[3], v[4], v[5]

Why do you think this variable length collection of data needs
individual names?

Now, if after consideration there is still some compelling reason to
generate names, you can use something like this with a dictionary
(possibly the one returned by globals()):

v = {}
for i in range(number_of_variables):
	name = "variable%d" % i
	v[name] = []

But again, Why?

In article <meh9-5C17A0.10445406042000 at news.cit.cornell.edu>,
Matthew Hirsch  <meh9 at cornell.edu> wrote:
>Hi All,
>
>Let's say I had something like:
>
>number_of_variables=int(raw_input('Enter number of variables: '))
>
>if number_of_variables==1:
>   variable1=[]
>elif number_of_variables==2:
>   variable1=[]
>   variable2=[]
>elif number_of_variables==3:
>   variable1=[]
>   variable2=[]
>   variable3=[]
>elif number_of_variables==4:
>   variable1=[]
>   variable2=[]
>   variable3=[]
>   variable4=[]
>elif number_of_variables==5:
>   variable1=[]
>   variable2=[]
>   variable3=[]
>   variable4=[]
>   variable5=[]
>else:
>   print 'else'
>
>Is there a more efficient way of doing this? What if I wanted to create 
>100 variables (lists).  It doesn't make sense to write an if statement 
>for that many conditions.
>
>Thanks for your help,
>Matt





More information about the Python-list mailing list