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.
Yes, it is, there is no restriction about it. In C++ is also very common creating for loops with iterators.
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.
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.
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 .
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
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)
Use the power operator.
In [1]: [2**j for j in range(7)]
Out[1]: [1, 2, 4, 8, 16, 32, 64]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With