Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to make a "for" loop in python double my index value after each iteration?

In C++, I can easily write a for loop like below that achieves this purpose

for(int i = 1; i < 100; i *= 2){}

Is there any way to make a for loop in Python do the same thing? Or is the while loop the only way I can do this.

like image 280
Andy Cheng Avatar asked Mar 14 '17 07:03

Andy Cheng


People also ask

Can we use a double value as in index in a for loop?

Yes, it is, there is no restriction about it. In C++ is also very common creating for loops with iterators.

How do I loop a second index in Python?

If you want to iterate through a list from a second item, just use range(1, nI) (if nI is the length of the list or so). i. e. Please, remember: python uses zero indexing, i.e. first element has an index 0, the second - 1 etc. By default, range starts from 0 and stops at the value of the passed parameter minus one.

Can you increment i in a for loop?

Increment is an expression that determines how the loop control variable is incremented each time the loop repeats successfully (that is, each time condition is evaluated to be true). The for loop can proceed in a positive or negative fashion, and it can increment the loop control variable by any amount.

How do you increment a loop by 2 in Python?

The solution for to increment a for loop by 2 in Python is to use the range() function. This function allows you to specify three parameters: start , stop , and step .


3 Answers

for loops don't do any incrementing; they iterate over an iterable instead.

You can create a generator function that produces your number sequence as an iterable:

def powers_of_two(start, stop=None):
    if stop is None:
        start, stop = 1, start  # start at 1, as 0 * 2 is still 0
    i = start
    while i < stop:
        yield i
        i *= 2

for i in powers_of_two(129):
    # ...

Demo:

>>> for i in powers_of_two(129):
...     print(i)
...
1
2
4
8
16
32
64
128
like image 118
Martijn Pieters Avatar answered Oct 17 '22 14:10

Martijn Pieters


A generator can be written that, somewhat similar to the C++ for loop, takes an expression in form of a lambda function to manipulate the loop variable.

def func_range(func, start, stop=None):
    start, stop = (0, start) if stop is None else (start, stop)
    while start < stop:
        yield start
        start = func(start)


for i in func_range(lambda x: x*2, 1, 100):
    print(i)
like image 38
MB-F Avatar answered Oct 17 '22 13:10

MB-F


Use the power operator.

In [1]: [2**j for j in range(7)]
Out[1]: [1, 2, 4, 8, 16, 32, 64]
like image 1
Roland Smith Avatar answered Oct 17 '22 13:10

Roland Smith