[Tutor] Problems with iterations and breaking loops.
Emile van Sebille
emile at fenx.com
Wed Mar 17 16:39:56 CET 2010
On 3/17/2010 8:02 AM Karjer Jdfjdf said...
> I'm having problems with iterations and loops. So I'm curious about the best Python-way to do iterations of lists (in if, while etc statements) and breaking of loops.
> I have a list of tuples with 2 values. I want to perform calculations on all of these for each value in a range of values (e.g. 100 to 110).
> list_of_tuples = [(90629, 4644), (90706, 4617), (90729, 4709)]
> #start value
> n = 100
> #maximum value
> nmax = 110
> #First I create a list for the values
> range_list = 
> while n< int(nmax+1):
> n = n + 1
> print range_list
Look up the documentation for range -- there is an easier answer.
> for i in range_list:
> for t in list_of_tuples:
> val1 = t
> val2 = t
you can also unpack a tuple like:
for val1,val2 in list_of_tuples:
> print "do stuff with\t" + str(val1) + '\t' + str(val2) + \
> '\tfor rangevalue\t' + str(i)
> But I think that the rangelist is not needed and it can be done better (and faster for large quantities of data). I think it's better to have somethng like the code below. But I'm having problems with breaking the second loop and returning to the first loop. If I put in another while-statement befor the for-statement it stops after 1 run and it has to continue until the end of the range.
More information about the Tutor