How to change index of a for loop?
For your particular example, this will work:
for i in range(1, 10):
if i in (5, 6):
continue
However, you would probably be better off with a while
loop:
i = 1
while i < 10:
if i == 5:
i = 7
# other code
i += 1
A for
loop assigns a variable (in this case i
) to the next element in the list/iterable at the start of each iteration. This means that no matter what you do inside the loop, i
will become the next element. The while
loop has no such restriction.
Change value of index in a for loop python
Try to combine while loop with index ?
example:
lst = [1,2,3]
idx = 0
while idx < len(lst):
print(lst[idx])
idx += 1
if idx == len(lst):
# Reset index
idx = 0
EDIT
After debugging I found your errors - You havent been assigning the new delta
result to d
where you have been referencing from your code thus you never got the new indexes
cond = True
idx = 0
while cond and idx < len(l[d[1]]):
if d[0] > l[d[1]][idx]:
move(l[d[1]], l[d[2]])
s = sum_calc(l)
d = delta(s)
print("l =", l)
print("s =", s)
print("d =", d)
print("")
idx = 0
else:
cond = False
idx += 1
Output:
l = [[12, 3, 17], [14, 10], [12, 15]]
s = [32, 24, 27]
d = [8, 0, 1]
l = [[12, 17], [14, 10, 3], [12, 15]]
s = [29, 27, 27]
d = [2, 0, 1]
change index inside a for loop
Yes you can change index inside a for loop but it is too confusing. Better use a while loop in such case.
int j = 0;
while (j < result_array.length) {
if (item.equals(" ")) {
result_array[j] = "%";
result_array[j + 1] = "2";
result_array[j + 2] = "0";
j = j + 2;
} else
result_array[j] = item;
j++;
}
How to change values in a list while using for loop in Python? (without using index)
Python unlike many other languages is dynamically typed as in you don't need to initialize prepopulated arrays(lists) before populating them with data. Also a standard convention is list comprehensions which in lamens are in-line loops that return a list.
a = [1,2,3,4,5]
b = [num * 4 for num in a]
This is equivilent to:
a = [1,2,3,4,5]
b = []
for num in a:
b.append(num * 4)
changing loop index within loop
You can change the loop index within a for loop, but it will not affect the execution of the loop; see the Details section of ?"for"
:
The ‘seq’ in a ‘for’ loop is evaluated at the start of the loop;
changing it subsequently does not affect the loop. If ‘seq’ has
length zero the body of the loop is skipped. Otherwise the
variable ‘var’ is assigned in turn the value of each element of
‘seq’. You can assign to ‘var’ within the body of the loop, but
this will not affect the next iteration. When the loop terminates,
‘var’ remains as a variable containing its latest value.
Use a while loop instead and index it manually:
i <- 1
while(i < 100) {
# do stuff
if(condition) {
i <- i+3
} else {
i <- i+1
}
}
Python: Change index inside a for loop
enumerate
is managing the index here and it always goes to the next one. it doesn't "add 1 to i
" such that decreasing i
will move it backward, it produces the next index (from an internal counter) and the for
loop assigns that to i
before beginning the iteration.
If you want to be able to change the index during iteration, the traditional way is to manage the index yourself and use a while
loop instead of for
. However, an alternative is to write your own enumerator that allows the index to be adjusted. For example:
class ListEnumerator:
def __init__(self, seq, start=0):
self.seq = seq
self.index = start - 1
def __iter__(self):
return self
def __next__(self):
self.index += 1
if self.index < len(self.seq):
return self.index, self.seq[self.index]
else:
raise StopIteration
# go back the given number of elements
def back(self, off):
self.index -= (off + 1)
# skip ahead the given number of elements
def skip(self, off):
self.index += off
# process the same item again on next iteration
def again(self):
self.index -= 1
# process the previous item on next iteration
def prev(self):
self.index -= 2
# process the given item on next iteration
def set(self, index):
self.index = index - 1
Usage:
items = [3, 1, 4, 1, 5, 2, 7, 2, 9]
for i, x in (e := ListEnumerator(items)):
print(i, x)
if x == 1:
items[i] = 0
e.prev()
Modify the index inside the `for` loop with a range in Rust
Your code
for mut i in 2..points.len() {
// Do something
if some_condition {
i += 1;
}
}
will internally in the compiler be rewritten in simpler terms using loop
, into something like this:
let mut iter = (2..points.len()).into_iter();
loop {
if let Some(mut i) = iter.next() {
// Do something
if some_condition {
i += 1;
}
} else {
break
}
}
In this form, it should hopefully be more clear what actually happens here: i
is declared inside of the loop body, and assigned the next value from the range iterator at the beginning of each iteration. If you modify it, it will just be reassigned on the next iteration. Specifically, you can't change i
to affect anything outside of the current iteration of the loop.
C++: is it a bad method to change the index of a for loop while it's running?
It's absolutely fine. The language doesn't distinguish between changing the index in the loop body and changing it in the increment statement within the loop header.
for (initializer-statement; condition-statement; increment-statement)
loop-body;
is mostly equivalent to
{
initializer-statement;
while (condition-statement) {
loop-body;
increment-statement;
}
}
One difference is that a continue
statement within the loop body of a for
loop will still execute the increment-statement
, which could cause problems if you're not expecting it.
Also be careful that you don't create an infinite loop by overrunning your terminating condition.
Accessing the index in 'for' loops
Use the built-in function enumerate()
:
for idx, x in enumerate(xs):
print(idx, x)
It is non-pythonic to manually index via for i in range(len(xs)): x = xs[i]
or manually manage an additional state variable.
Check out PEP 279 for more.
Related Topics
How to Find Char in String and Get All the Indexes
Inserting Line at Specified Position of a Text File
How to Disable a Pylint Warning
How to Make a For-Loop Pyramid More Concise in Python
Only Extracting Text from This Element, Not Its Children
How to Display Full Output in Jupyter, Not Only Last Result
Heatmap in Matplotlib with Pcolor
How to Properly Assert That an Exception Gets Raised in Pytest
Python & MySQL: Unicode and Encoding
Why Do I Get Typeerror: Can't Multiply Sequence by Non-Int of Type 'Float'
Transparent Background in a Tkinter Window
How to Replace Two Things at Once in a String
Save Classifier to Disk in Scikit-Learn
Python Dictionary from an Object's Fields
Unpacking a List/Tuple of Pairs into Two Lists/Tuples
How to Account for Period (Am/Pm) Using Strftime
Numpy Sum Elements in Array Based on Its Value
Difference Between Methods and Functions, in Python Compared to C++