0

I have while loop in for loop. And, i want to update value l from while loop to for loop. Because, on this case is, for example: l==5 is in while loop, l==1 is in for loop.

  for l in range(len(csvLines)):
     if ";" in str(csvLines[l][:2]):
         objectType = int(csvLines[l][:1])
         while objectType == 0:
             l = l+1
             if ";" in str(csvLines[l][:2]):
                 objectType = int(csvLines[l][:1])
             else:
                 objectType = int(csvLines[l][:2])
         else:
             pass
     else:
         objectType = int(csvLines[l][:2])
Luk
  • 135
  • 2
  • 10
  • Make a different variable you're `l` are getting redefined but I don't quite get what you're trying to do here – abccd Feb 28 '17 at 08:19

1 Answers1

0

you can change l for the current for iteration, but as soon as the next for iteration begins, l is assigned the next value of range. If you want to modify iteration index, use while for example like this.

l = 0  # you have to initialize it manually
while l < len(csvLines):
   ...
   l += 1   # you have to increase it manually at the end of the current iteration

Note: when increasing l in the loop, you have to make sure that it's still < len(csvLines) or next access to csvLines[l] will fail.

Jean-François Fabre
  • 126,787
  • 22
  • 103
  • 165
  • *but I'd avoid that in Python 2* - I'd avoid it *completely* never mind the Python version... :) – Jon Clements Feb 28 '17 at 08:23
  • `range` check is very fast in python 3. Check Martijn Pieters best post on the subject, let me find it here it is: http://stackoverflow.com/questions/30081275/why-is-1000000000000000-in-range1000000000000001-so-fast-in-python-3?s=2|0.5508 – Jean-François Fabre Feb 28 '17 at 08:24
  • A simple integer comparison check is 1) more obvious as to the intent and 2) faster than the membership test on the range object... By the looks of it - the OP doesn't even need the counter variable, but we'll ignore that for the moment... – Jon Clements Feb 28 '17 at 08:27
  • okay, no need for that. But the counter variable is needed everywhere for `csvLines[l]` – Jean-François Fabre Feb 28 '17 at 08:29
  • 2
    You really should not use `l in range(N)` for such tests, because if `l` is ever *not* an integer you suddenly turned a simple O(1) check into a slow O(N) check. Stick to chained comparisons (or a simple ` – Martijn Pieters Feb 28 '17 at 08:38
  • that is some subtle trap. Duly noted (answer already edited, but I thought that `while l in range` looked good) – Jean-François Fabre Feb 28 '17 at 12:21