Question on for loop

Alister alister.ware at ntlworld.com
Fri Jan 4 05:16:44 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 I was
> thinking of var_series=['var1','var2','var3']
> for var in var_series:
>   for fruit in fruits:
>        print var,fruits
> 
> If any one can kindly suggest.
> 
> Regards,
> Subhabrata
> 
> NB: Apology for some alignment mistakes,etc.

if you really want to do this (& I agree with the other replies that this 
is unlikely to be a good idea) then you could simply unpack the list

var1,var2,var3=fruits

of course if your list is of unknown length then this again becomes 
impractical.

for most programming requirements there is a simple solution, if you find 
your approach is not easily implemented it is probably a good time to re-
asses your approach, more of the than not you have been given a bum steer 
and are heading down the wrong road.

See http://thedailywtf.com for an almost limitless supply of examples of 
programmers continuing down the wrong road ;-) 

-- 
There's nothing worse for your business than extra Santa Clauses
smoking in the men's room.
		-- W. Bossert



More information about the Python-list mailing list