Modify range() during for loop [duplicate] - python

This question already has answers here:
Changing the number of iterations in a for loop
(8 answers)
Closed 1 year ago.
can I modify range() during for loop?
for i in range(10):
if something:
pass
# change range
print(i)
An example:
Let method something be i == 5 and the body will decrease range by one.
Expected output:
0
1
2
3
4
5
5
6
7
8
9
I have a little more complex range() like range(0, len(data), 1024).
Thanks for any help!

You cannot modify the generator used in the for loop during the iteration process. Instead, you could refactor your code using a while loop. For example, if your range is range(start, stop, step) (using the notation similar to that used in the Python documentation), you can write the loop as follows:
i = start
while i < stop:
# do stuff
i += step
This allows you to modify i however you'd like inside the while loop.

Try the following:
i = 0
while i <= 5:
print(i)
i = i + 1
i = i - 1
while i <= 10:
print(i)
i = i + 1
As others have said, it is probably best to use a while loop in this scenario and manually increase your value every time the loop is performed, rather than using a for loop.

You can kind of modify it within the for loop using break keyword.
start_val = 0
stop_val = 10
for i in range(start_val ,stop_val):
if i==5:
start_val = 5
print(i)
for i in range(start_val ,stop_val):
print(i)
break
print(i)
This gives expected output:
0
1
2
3
4
5
5
6
7
8
9

Related

Why are there different outputs for 'while' loop depending on postion of 'print' statement? [duplicate]

This question already has answers here:
why last output also varies in this block of python code?
(2 answers)
Closed 3 months ago.
I am new to Python and I encountered this problem using while loops. Depending on where the print statement is located (after 'while' or at end of loop) I get 2 different outputs.
# 'While' loop example with 'print' after 'while' statement
i = 2
x = 10
while i < x: # Perform loop until this condition no longer true: i is less than x
print(i) # Print output of loop iteration
i = i + 2 # Loop to perform: add 2 to i
Output:
2
4
6
8
# 'While' loop example with 'print' at end of loop
i = 2
x = 10
while i < x: # Perform loop until this condition no longer true: i is less than x
i = i + 2 # Loop to perform: add 2 to i
print(i) # Print output of loop iteration
Output:
4
6
8
10
I thought the output would be the same. How is Python reading the loops in each case?
Also this is the first time I have posted here, so if I am not following the correct format please let me know.
Try to reproduce it by yourself, with a pencil on a blank paper.
First case:
At first i is equal to 2, so print(i) will print 2, then increment it by 2, now i is equal to 4
Then printing i will print 4, then you add 2, so now i is equal to 6...
When i = i+2 changes the value of i to 10, at the next iteration i < x is false, so you exit the loop.
Second case:
At first i is equal to 2, but you add immediately 2, so i is equal to 4 and then you print it
Then you add 2, so now i is equal to 6 and you print it...
When i = i+2 changes the value of i to 10, you print it last time and at the next iteration i < x is false, so you exit the loop.

Nested loop not printing the first element but going to 2nd element?

I have a very simple piece of code but it's driving me nuts to understand the logic.
for a in range(6):
print("\t\t")
for j in range(a):
print(a, end=" ")
The output is:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
the first value to be printed is supposed to be 0 since the range(6) starts from 0 and a and j wrapped in for loops both are supposedly getting 0 as first element but it starts from 1 instead.
That comes, because the for loop in range 0 will not be executed. You can not execute something if that has to go 0 times. To make it run as you would like to be, you would have to write following code:
for a in range(6):
print("\t\t")
for j in range(a + 1):
print(a, end=" ")
The value of a is the number of iterations of the inner loop. (Note that the question should have the j loop indented, so that it is inside the a loop, in order to get the output shown.)
On the first iteration, a is 0, and then range(0) will give an empty sequence, which give zero iterations when iterating over it. (Specifically a StopIteration will occur the first time a value is fetched.)
On the next iteration of the outer loop, there will be one j value when iterating, and so forth.
So 0 is printed 0 times (i.e. not at all), then 1 is printed once, 2 is printed twice, ... , 5 is printed 5 times.
You are not using the values of j at all, but they will be:
when a is 0: no iterations
when a is 1: j is 0 only
when a is 2: j is 0, 1
... etc, up to ...
when a is 6: j is 0, 1, 2, 3, 4, 5
Note that in fact it is conventional to use a variable name _ for a loop variable whose value you do not use (at least assuming that it not inside a loop already using _). If you adhere to this convention (i.e. use _ instead of j) and also fix the indentation, then your code might look like:
for a in range(6):
print("\t\t")
for _ in range(a):
print(a, end=" ")

In python, executing the runtime input in for loop it prints all values. why?

I am new to python. I have executed for loop with runtime input.
Loop 1:
a = int(input("enter\n"))
for i in range(1, a+1):
print(i)
The output prints all values from 1 to 5.
Loop2:
for i in range(1, 5):
print(i)
The output print the values from 1 to 4.
Please someone explain the different between the above two for loop.
In the range function in python, the last argument is exclusive. This means that it represents the stopping point of the range but is not included in the output. Since the first loop has a+1 as the last argument, a will be included in the output.
Did you have a look at https://docs.python.org/fr/3/library/stdtypes.html#range ?
To keep things easy, range(a, b) will return an iterator that goes from a to b - 1.
Thus, your first loop will print 1 to (a + 1) - 1 = a, and your second loop will print 1 to 5 - 1 = 4.
for i in range(0,5):
print(i)
Prints values from 0 to 4 because when the iteration comes to the value 5 it becomes excluded and it won't print the value.
So we add 1 to the final value(maximum) to print till the value we want.
for i in range(0,6):
print(i)
GIVES:
0
1
2
3
4
5

How to get compare variables of a list individually?

So I have this code below that I'm trying to make, to where it will sort any list I give it so the lowest variable will be at the beginning, in position [0]. The problem I think is when the while loop comes in it compares uList[y] to the sum of uList[z:p] but, I was hoping it would compare it to each of the numbers individually so that if uList[y] is greater than ANY variable in uList[z:p] it would step into the loop how ever it does not. How would I go about making it compare the variables individually rather to the sum of them all, if that is whats happening.
Code:
import random
import sys
import os
import time
clear = lambda: os.system('cls')
clear()
y = 0
z = 1
x = 0
nNum = 1
uList = []
sList = []
listL = int(raw_input("How many elements would you like to be in your list?"))
clear()
while x < listL:
uList.append(int(raw_input("Num %s:" %(nNum))))
x = x + 1
nNum = nNum + 1
p = len(uList) - 1
clear()
print("Your list was %s!" %(uList))
while z <= p:
while uList[y] > uList[z]:
j = uList[y]
del uList[y]
uList.append(j)
print(uList)
P.S. Any other tips or advice on anything about my code would be greatly appreciated as I am very obviously knew to python and coding in general lol, thank you so much!
The comments under your answer suggest that you have already solved your problem but because you asked for some Python advice: the 'pythonic' way to iterate is by using a for loop with a range instead of a while loop.
i = 0
while i < 10:
i += 1
Becomes:
for i in range(10):
pass
If you want to get the indices of the sequence you are iterating over you can use enumerate.
my_list = [*range(10)] # this is basically a for loop creating a list
for index, element in enumerate(my_list):
print(index, element)
This gives you:
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
One last thing though. I am not sure if you are using Python 2 or 3 because you are using raw_input (Python 2) and print() (Python 2 or 3). If you are learning Python or programming in general I would recommend you go with Python 3 because it is easier to learn in some aspects and offers various improvements in efficiency and effectiveness.

Change value of iterator of parent for loop in nested for loop?

So, I am trying to solve competitive programming using Python and came across a problem which required use of nested loops. I used nested for loop and incremented the value of iterator of parent for loop if certain condition is met in the child for loop. But when the child for loop ends, the value of iterator of parent for loop doesn't change.
Example:
for i in range(5):
print "When i = %d" % (i)
for j in range(i+1,5):
print j
if j % 2 == 0:
i = j
Output:
When i = 0
1
2
3
4
When i = 1
2
3
4
....
How to increment the value of I and make the loop run less times, as I want to decrease the CPU time and cycles?
in python, if you wanna change the value of the iterator in a loop, you should use while loop. Your question isn't clear enough about what you want to achieve, but an example would be:
i = 0
while i < 5:
print "When i = %d" % (i)
i+=1
for j in range(i,5):
print j
if j % 2 == 0:
i = j
Your problem isn't clear enough, but if you wanted to change the for loop you should directly consider using the while loop
I may have been incorrect in my assertion of variable scope, but regardless, the for loop follows the looping variable definition independent of how you attempt to define the looping variable within the loop.
Here is an example of what's happening with your script. No matter how you set i, it will still go through the entire range(5).
In [1]: for i in range(5):
print(i)
i=10
print(i)
Out [1]: 0
10
1
10
2
10
3
10
4
10
You need a while loop instead of a for loop, so you can redefine any variable within the loop. If I understood your exact problem correctly, I think you're looking for this:
i = 0 # initialize i
while i<4: # ensure i stops at no more than 4 in the final iteration
print "When i = %d" % i
for j in range(i+1,5):
print j
if j % 2 == 0:
i = j
break # break out of the j loop if this condition is met
else: # iterate i if none of the 'j %...' conditions are met ('break' is not encountered)
i+=1

Categories

Resources