0

I am having an issue with calling a for loop if it's range is increasing.

I have a table (list of lists):

for i in range(0, len(table)):
     if len(table[i]) > 10:
          new_row = table[i][11:]
          table.insert(i+1, [])
          for val in new_row:
               table[i+1].append(val)

e.g The length of table was 50 and there are a number of rows where I have more than 10 values. After every new row is created (table.insert(i+1, []), the length of the table increases, so by the time the loop gets to row 49 where the row list is greater than 10, it's actual row number becomes greater than the range of the loop.

How can I make the loop know that the range increases? At the moment, only rows upto 50 have if condition applied

I tried adding a count variable before the loop:

count = 0
for i in range(0, len(table)+count):
    if len(table[i]) > 10:
         new_row = table[i][11:]
         table.insert(i+1, [])
         for val in new_row:
              table[i+1].append(val)
         count = count + 1

This did not seem to help! Maybe some sort of recursive function within the for loop to constantly poll the table length? I'm not too sure.

Thanks

arsenal88
  • 1,040
  • 2
  • 15
  • 32
  • The range call is made once at the beginning of the loop, so you can't change this after the loop has started. You should probably use a `while` loop instead of a `for` loop. – pcarter May 10 '17 at 14:05
  • refer http://stackoverflow.com/questions/11905606/changing-the-number-of-iterations-in-a-for-loop – JkShaw May 10 '17 at 14:06

2 Answers2

1

Is this what you are looking for?

idx = 0
while True:
    try:
        lst = table[idx]
    except IndexError:
        break
    if len(lst) > 10:
        table.insert(idx+1, lst[10:])
        # You probably want to cut current lst here as well?
        # table[idx] = lst[:10]
    idx += 1
freakish
  • 54,167
  • 9
  • 132
  • 169
0

you can use while loop for this purpose!

count = 0
i=0 #initial value
while table: #your iterating loop until table holds a value!
    if len(table[i]) > 10:
         new_row = table[i][11:]
         table.insert(i+1, [])
         for val in new_row:
              table[i+1].append(val)
         count = count + 1
    i+=1 #increment by 1
Keerthana Prabhakaran
  • 3,766
  • 1
  • 13
  • 23