For loop with custom steps in python

for-loop, python

Solution

First and foremost: Python `for` loops are not really the same thing as a C `for` loop. They are For Each loops instead. You iterate over the elements of an iterable. `range()` generates an iterable sequence of integers, letting you emulate the most common C `for` loop use case.

However, most of the time you do not want to use `range()`. You would loop over the list itself:

for elem in reversed(some_list):
    # elem is a list value

If you have to have a index, you usually use `enumerate()` to add it to the loop:

for i, elem in reversed(enumerate(some_list)):
    # elem is a list value, i is it's index in the list

For really 'funky' loops, use `while` or create your own generator function:

def halved_loop(n):
    while n > 1:
        yield n
        n //= 2

for i in halved_loop(10):
    print i

to print `10`, `5`, `2`. You can extend that to sequences too:

def halved_loop(sequence):
    n = -1
    while True:
        try:
            yield sequence[n]
        except IndexError:
            return
        n *= 2

for elem in halved_loop(['foo', 'bar', 'baz', 'quu', 'spam', 'ham', 'monty', 'python']):
    print elem

which prints:

python
monty
spam
foo

Problem

I can make simple for loops in python like: ``` for i in range(10): ``` However, I couldn't figure out how to make more complex ones, which are really easy in c++. How would you implement a for loop like this in python: ``` for(w = n; w > 1; w = w / 2) ``` The closest one I made so far is: ``` for w in reversed(range(len(list))) ```

Original source