Tutorial :Python for loop question



Question:

I was wondering how to achieve the following in python:

for( int i = 0; cond...; i++)    if cond...      i++; //to skip an run-through  

I tried this with no luck.

for i in range(whatever):    if cond... :      i += 1  


Solution:1

Python's for loops are different. i gets reassigned to the next value every time through the loop.

The following will do what you want, because it is taking the literal version of what C++ is doing:

i = 0  while i < some_value:      if cond...:          i+=1      ...code...      i+=1  

Here's why:

in C++, the following code segments are equivalent:

for(..a..; ..b..; ..c..) {      ...code...  }  

and

..a..  while(..b..) {       ..code..       ..c..  }  

whereas the python for loop looks something like:

for x in ..a..:      ..code..  

turns into

my_iter = iter(..a..)  while (my_iter is not empty):      x = my_iter.next()      ..code..  


Solution:2

There is a continue keyword which skips the current iteration and advances to the next one (and a break keyword which skips all loop iterations and exits the loop):

for i in range(10):      if i % 2 == 0:        # skip even numbers        continue       print i  


Solution:3

Remember that you are iterating over the elements in the list, and not iterating over a number.

For example consider the following:

for i in ["cat", "dog"]:    print i  

What would happen if you did i+1 there? You can see now why it doesn't skip the next element in the list.

Instead of actually iterating over all values, you could try to adjust what is contained inside the list you are iterating over.

Example:

r = range(10)  for i in filter(lambda x: x % 2 == 0, r):    print i  

You can also consider breaking up the for body into 2. The first part will skip to the next element by using continue, and the second part will do the action if you did not skip.


Solution:4

You can explicitly increment the iterator.

whatever = iter(whatever)  for i in whatever:      if cond:          whatever.next()  

You will need to catch StopIteration if cond can be True on the last element.


Solution:5

There is an alternate approach to this, depending on the task you are trying to accomplish. If cond is entirely a function of the input data you are looping over, you might try something like the following:

def check_cond(item):      if item satisfies cond:          return True      return False    for item in filter(check_cond, list):      ...  

This is the functional programming way to do this, sort of like LINQ in C# 3.0+. I'm not so certain it's all that pythonic (for a while Guido van Rossum wanted to remove filter, map and reduce from Python 3) but it certainly is elegant and the way I would do it.


Solution:6

You can't trivially "skip the next leg" (you can of course skip this leg with a continue). If you really insist you can do it with an auxiliary bool, e.g.

skipping = False  for i in whatever:    if skipping:      skipping = False      continue    skipping = cond    ...  

or for generality with an auxiliary int:

skipping = 0  for i in whatever:    if skipping:      skipping -= 1      continue    if badcond:      skipping = 5  # skip 5 legs    ...  

However, it would be better to encapsulate such complex looping logic in an appropriate generator -- hard to give examples unless you can be a bit more concrete about what you want though (that "pseudo-C" with two presumably 100% different uses of the same boolean cond is REALLY hard to follow;-).


Solution:7

for i in filter(lambda x:x!=2,range(5)):  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »