How to make for loop faster in python?

Is there a non-while loop Python equivalent of Java / C standard for loop with counter?

  • In particular, I'd like to replicate the following functionality in Python, without using a while loop. for (int i = 0; i < 10; i++){ if (i == 5) i++; } A more realistic example, to set the context: for (int i = 0; i < myarray.length; i++){ if (myarray[i] == 7) i++; //want to skip the next element in the list. } xrange will do all of that, except for being able to conditionally skip indices this way.

  • Answer:

    In response to your "realistic example", you can loop over a generator [1]. >>> i_gen = (i for i in xrange(10) if i != 7) >>> for i in i_gen: ... print i To editorialize, you shouldn't write Python like you write Java or C [2]. Learn the idioms. [1] http://docs.python.org/tutorial/classes.html#generators [2] http://faassen.n--tree.net/blog/view/weblog/2005/08/06/0

Noah Seger at Quora Visit the source

Was this solution helpful to you?

Other answers

To skip an element you'll want to advance the iterator: it = iter(thing_to_iterate) for i in it: if i == stuff: it.next() The only danger here is if your are on the last element and try to skip ahead it will throw StopIteration.  This can be avoided by writing small utility function: def advance(it): try: it.next() except StopIteration: pass Another option is to use filter()/itertools.ifilter() to remove undesirable elements: for i in filter(lambda x: x != 7, thing_to_iterate): ... stuff ...

Adam Hupp

Java ish solution for i in xrange(10):       if i == 7:         continue       print i or Python ish solution. This is very similar to the generator posted [i for i in xrange(10) if i != 7]

Adam Ilardi

If you really want to do this, you can define your own iterator, however, I don't think it's very "pythonic". class Citerator: def __init__(self, start, stop, inc): self.index = start self.stop = stop self.inc = inc def __iter__(self): return self def next(self): index = self.index if index >= self.stop: raise StopIteration self.index += self.inc return index def skip_next(self): self.index += self.inc myarray = list(range(10)) myiter = Citerator(0, len(myarray), 1) for i in myiter: if myarray[i] == 7: myiter.skip_next() print i

Ken Quon

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.