More about variables

Michael Scharf Michael.Scharf at gmx.de
Thu Apr 6 12:22:38 EDT 2000


Matthew Hirsch 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.

Just do:

for i in range(number_of_variables):
    vars()["variable%s" %(i+1)]=[]

Michael
-- 
     ''''\     Michael Scharf
    ` c-@@     TakeFive Software GmbH, a Wind River Company
    `    >     http://www.WindRiver.com
     \_ V      mailto:Michael.Scharf at gmx.de



More information about the Python-list mailing list