Python For loops in While loop, starting for loop with a specific value
Solution 1
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
Solution 2
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.
Solution 3
In Python, stepping over a collection in the traditional sense is not ideal. The ability to loop - to iterate - over an object is controlled by the object, so you don't need to manually step through counters as you would in the for
loop in C++.
As I understand it, what you are trying to do here is execute the same piece of code over each item in a list
(there are no arrays in Python), a multiple number of times.
To do that:
def whatever_function(foo):
# some code here that works on each item on the list
# foo is an item of the list
while True:
map(whatever_function, some_list)
peter1234
Updated on June 04, 2022Comments
-
peter1234 almost 2 years
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?