Question on for loop

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Jan 4 00:48:24 EST 2013


On Thu, 03 Jan 2013 12:04:03 -0800, subhabangalore wrote:

> Dear Group,
> If I take a list like the following:
> 
> fruits = ['banana', 'apple',  'mango'] 
> for fruit in fruits:
>    print 'Current fruit :', fruit
> 
> Now,
> if I want variables like var1,var2,var3 be assigned to them, we may
> take, var1=banana,
> var2=apple,
> var3=mango
> 
> but can we do something to assign the variables dynamically

Easy as falling off a log. You can't write "var1", "var2" etc. but you 
can write it as "var[0]", "var[1]" etc.

var = ['banana', 'apple',  'mango'] 
print var[0]  # prints 'banana'
print var[1]  # prints 'apple'
print var[2]  # prints 'mango'



Of course "var" is not a very good variable name. "fruit" or "fruits" 
would be better.




-- 
Steven



More information about the Python-list mailing list