Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python For loops in While loop, starting for loop with a specific value

I've started learning Python a few days ago and I ran into a program while coding something.

Here's what I want to do using C++ code

number = SOME_NUMBER;
while(1) {
    for(int i=number; i<sizeOfArray; i++) {
        // do something
    }
    number = 0;
}

Basically, for the very first iteration of my for loop, I want to start i at number. Then for every other time i go through the for loop, I want to start it at 0.

My kind of hacky idea that I can think of right now is to do something like:

number = SOME_NUMBER
for i in range(0, len(array)):
    if i != number:
        continue
    // do something

while True:
    for i in range(0, len(array)):
        // do something

Is this the best way or is there a better way?

like image 560
peter1234 Avatar asked Sep 12 '25 21:09

peter1234


2 Answers

what is the problem with this?

starting_num = SOME_NUMBER
while True:
    for i in xrange(starting_num, len(array)):
        # do code
    starting_num = 0

it does exactly what you want.

however, i think there are better ways to do things especially if the solution seems "hacky".

if you gave an idea of what you wanted to do, maybe there is a better way

like image 105
Inbar Rose Avatar answered Sep 15 '25 12:09

Inbar Rose


I don't see why you couldn't just do the same thing you are in C:

number = SOME_NUMBER
while True:
    for i in range(number, len(array)):
        # do something
    number = 0

BTW, depending on which version of Python you're using, xrange may be preferable over range. In Python 2.x, range will produce an actual list of all the numbers. xrange will produce an iterator, and consumes far less memory when the range is large.

like image 35
John Szakmeister Avatar answered Sep 15 '25 11:09

John Szakmeister