Reputation: 3
I am writing a piece of code the this is the scenario I am facing.
How to update the list which is in for-condition, and for the next iteration, the list in for-condition is updated?
Eg.,
list = [0,1,2]
for i in list:
print list[i]
if list[i] == 0:
list.append(3)
The entry '3' should get updated in the list in for-condition.
Is it possible to update the list in for-condition dynamically?
Thanks in advance.
Upvotes: 0
Views: 800
Reputation: 235994
Be aware that your loop is incorrect, in Python this snippet:
for e in lst:
… Iterates over each element e
in lst
, and e
is not an index, it's an element - so all the parts in the question where you wrote list[i]
are incorrect, they should have been simply i
. Try this solution instead, it's equivalent and less error prone:
lst = [0, 1, 2]
print(lst)
lst += [3] * lst.count(0) # add as many 3s at the end as there are 0s in the list
Notice that it's never a good idea to modify a list at the same time you're traversing it. Also, don't use list
as a variable name, there's a built-in function with that name.
Upvotes: 3
Reputation: 251355
Yes, if you do that, it will work. However, it's usually not a good idea, because it can create confusing interactions between the iteration and the loop-body action. In your example, you add an element at the end, but if, for instance, you change an element in the middle, you may or may not see the change depending on where you are in the list when it happens. (For instance, you could change the value of an element you already iterated past.)
Also, you shouldn't name a variable list
, as that shadows the built-in type called list
.
Upvotes: 3